C#: Creating lists of generic containers?

本秂侑毒 提交于 2019-12-24 11:44:25

问题


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:

  1. 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?

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!