我在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);
}
这可以做这样的事吗?
答案 0 :(得分:5)
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);
}
}
如果您不知道类型或具有不同类型的多个对象,请声明A的实例,如下所示:
A<object> myClass = new A<object>();
myClass.Fill(new object(), new object());
否则,如果你知道类型,你可以这样做:
A<int> myInts = new A<int>();
myInts.Fill(1, 2, 5, 7);
答案 1 :(得分:3)
是
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);
}
最好使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);
}
答案 2 :(得分:2)
您将需要使用反射来实例化IList <
T >
,其中T在运行时才知道。
请参阅以下MSDN文章,它比我更好地解释了它(向下滚动到有关如何构造泛型类型的部分): http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx
这是一个简短的例子:
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..
答案 3 :(得分:1)
您可能需要考虑一个通用类:
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);
}
答案 4 :(得分:0)
System.Collections.Generic.List<T>
?