Generic list of generic objects
Yes, generics is a good choice. The key to achieving type-safety (and being identify the type with the Type
property is to add an abstraction between the list and Field<T>
class.
Have Field<T>
implement the interface IField
. This interface doesn't need any members.
Then declare your list as being List<IField>
.
That way you constrain the list to only contain fields, but each field can be of a different type.
To then read the values later, just do
foreach(var field in list)
{
var type = field.Type;
....
}
I suggest you to define an interface and Field<T>
implements that interface
public interface IField
{
}
public class Field<T> : IField
{
public string Name { get; set; }
public Type Type
{
get
{
return typeof(T);
}
}
public int Length { get; set; }
public T Value { get; set; }
}
so you can write this code:
var list = new List<IField>();
now this list can contain any object of type Field<T>