开发者

Generic List created at runtime

开发者 https://www.devze.com 2022-12-24 09:21 出处:网络
i neeed something like this in C#.开发者_如何学Python. have list in class but decide what will be in list during runtime

i neeed something like this in C#.开发者_如何学Python. have list in class but decide what will be in list during runtime

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<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:

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.

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号