简体   繁体   English

在运行时创建通用列表

[英]Generic List created at runtime

i neeed something like this in C#.. have list in class but decide what will be in list during runtime 我在C#中需要这样的东西..在类中有列表,但决定在运行时将在列表中

class A
{
    List<?> data;
    Type typeOfDataInList;
}

public void FillData<DataTyp>(DataTyp[] data) where DataTyp : struct
{
    A a = new A();
    A.vListuBudouDataTypu = typeof(DataTyp);
    A.data = new List<A.typeOfDataInList>();
    A.AddRange(data); 
}

Is this possible to do something like this ? 这可能做这样的事情吗?

class A<T>
{
    public readonly List<T> Data = new List<T>();
    public Type TypeOfDataInList { get; private set; }

    public A()
    {
        TypeOfDataInList = typeof(T);
    }

    public void Fill(params T[] items)
    {
        data.AddRange(items);
    }
}

If you don't know the type or have multiple objects of different types, declare an instance of A like this: 如果您不知道类型或具有多个不同类型的对象,请声明A的实例,如下所示:

A<object> myClass = new A<object>();
myClass.Fill(new object(), new object());

Otherwise if you know the type, you can do this: 否则,如果您知道类型,则可以执行以下操作:

A<int> myInts = new A<int>();
myInts.Fill(1, 2, 5, 7);

Yes. 是。

class A
{
    IList data;
    Type typeOfDataInList;
}

public void FillData<T>(T[] data) where T : struct
{    
    A a = new A();
    A.typeOfDataInList = typeof(T);
    A.data = new List<T>(data);
}

It would be better to make the A class generic: 最好使A类通用:

class A<T>
{
    IList<T> data;
    Type typeOfDataInList;
}

public void FillData<T>(T[] data) where T : struct
{    
    A<T> a = new A<T>();
    a.typeOfDataInList = typeof(T);
    a.data = new List<T>(data);
}

You are going to need to use reflection to instantiate an IList < T > where T is not known until runtime. 您将需要使用反射实例化一个IList < T > ,其中T直到运行时才知道。

See the following MSDN article, which explains it better than I could (scroll down to the section on how to construct a generic type): http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx 请参阅下面的MSDN文章,该文章比我能更好地解释它(向下滚动到有关如何构造泛型类型的部分): http : //msdn.microsoft.com/zh-cn/library/b8ytshk6.aspx

Here is a short example: 这是一个简短的示例:

        Type listType = typeof(List<>);
        Type runtimeType = typeof(string); // just for this example
        // assert that runtTimeType is something you're expecting
        Type[] typeArgs = { runtimeType };
        Type listTypeGenericRuntime = listType.MakeGenericType(typeArgs);
        IEnumerable o = Activator.CreateInstance(listTypeGenericRuntime) as IEnumerable;
        // loop through o, etc..

You might want to consider a generic class: 您可能要考虑一个通用类:

public class A<T> where T : struct
{
    public List<T> data;
    public Type type;
}

public void FillData<DataType>(DataType[] data) where DataType : struct
{
    A<DataType> a = new A<DataType>();
    a.data = new List<DataType>();
    a.AddRange(data);
}

System.Collections.Generic.List<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM