问题
I have a situation in which I have a data container that looks something like this:
public class DataContainer<T>
{
public T GetData { get; private set; }
public DataContainer(T data)
{
this.GetData = data;
}
}
But unfortunately I need to have a list of these containers where the generic parameter of each is not known until runtime and can vary from element to element. I initially attempted to run with something like:
IList<DataContainer<dynamic>> containerList = new List<DataContainer<dynamic>>();
containerList.add((dynamic)new DataContainer<int>(4));
containerList.add((dynamic)new DataContainer<string>("test"));
Which unfortunately does not work (run into a RuntimeBinderException). I initially attempted casting to (DataContainer) but I get an InvalidCastException there.
My question has two parts:
I understand that I'm probably abusing 'dynamic' to try to get the behavior I want, but can someone explain why the above won't work?
What's the best way to approach this situation? Should I push the dynamic into the 'GetData' for the DataContainer and de-genericize it?
Thanks so much!
回答1:
You can do something like this:
public interface IDataContainer
{
object GetData{get;set;}
}
public class DataContainer<T> : IDataContainer
{
public T GetData { get; private set; }
object IDataContainer.GetData
{
get { return this.GetData; }
set { this.GetData = (T)value; }
}
public DataContainer(T data)
{
this.GetData = data;
}
}
Then you can do:
IList<IDataContainer> containerList = new List<IDataContainer>();
containerList.Add(new DataContainer<string>("test"));
containerList.Add(new DataContainer<int>(234));
回答2:
You can make a non-generic baseclass version of DataContainer and use that for your List's generic type
来源:https://stackoverflow.com/questions/19852034/c-creating-lists-of-generic-containers