C#:创建通用容器列表? [英] C#: Creating lists of generic containers?
问题描述
我有一个情况,我有一个数据容器看起来像这样:
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"));
其中不幸的是不运行(运行到RuntimeBinderException)。我最初尝试转到(DataContainer),但是我收到一个InvalidCastException。
Which unfortunately does not work (run into a RuntimeBinderException). I initially attempted casting to (DataContainer) but I get an InvalidCastException there.
我的问题有两部分:
-
我知道我可能会滥用动态来尝试获得我想要的行为,但有人可以解释为什么上述不行吗?
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?
解决这种情况最好的方法是什么?我应该将动态数据推送到DataContainer的GetData并将其拆分吗?
What's the best way to approach this situation? Should I push the dynamic into the 'GetData' for the DataContainer and de-genericize it?
非常感谢!
推荐答案
你可以这样做:
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;
}
}
然后你可以做:
IList<IDataContainer> containerList = new List<IDataContainer>();
containerList.Add(new DataContainer<string>("test"));
containerList.Add(new DataContainer<int>(234));
这篇关于C#:创建通用容器列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!