Answer the question
In order to leave comments, you need to log in
How to create a field of type Generic List in a class?
Can you please tell me how to create a type field Generic List<T>
in a class? Those. I need to be able to write a List of any type in the field when creating an instance of the class - for example, List<Album>
or List<Photo>
.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lab1
{
public partial class AddForm : Form
{
public string itemToAdd { get; set; }
public List<T> list { get; set; }
public AddForm()
{
InitializeComponent();
}
}
}
Answer the question
In order to leave comments, you need to log in
If you want exactly " when creating an instance of a class , a List of any type could be written in the field", then the generic type must be defined at the compilation stage, and if you did not explicitly specify its type, then the compiler tries to find the class T in the current namespace, and its You don't, hence the error.
If you need to use a generic field inside a class, then you must define the class with the same type.
public partial class AddForm<T> : Form where T: class
{
public string itemToAdd { get; set; }
public List<T> list { get; set; }
public AddForm()
{
InitializeComponent();
}
}
public partial class AddForm : Form
{
public string itemToAdd { get; set; }
public List<object> list { get; set; }
public AddForm()
{
InitializeComponent();
}
}
var albums = form.list.OfType<Album>();
var photos = form.list.OfType<Photo>();
Maria , the List collection can only store objects of one type, so it seems that putting a couple of different types (Album and Photo) into it will no longer work. But this is only at first glance.
One of the pillars of OOP can come to the rescue: inheritance. If you make your Album and Photo types inherit from the same base type, such as MyObject, then you can create a list of common elements in the form: List.
This way you can add both Album and Photo to this list, but I'm sure that the next question will be how to get them from this list. Come to Toaster again. :-)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question