反照创建 Ilist
反射创建 Ilist<t>
从动态创建的类,再创建Ilist<动态类> 的集合,该怎么创建?
Type t = Type.GetType("动态类名");
//不是要这个 object o = Activator.CreateInstance(t);
//而是要这个 IList<t> it = new List<t>();
给个思路也行。
------最佳解决方案--------------------
这个意思么?比如我的例子中最后的list就是一个Student的泛型集合。
------其他解决方案--------------------
public class cls<T>
{
public IList<T> GetList()
{
var listType = typeof(List<>).MakeGenericType(typeof(T));
return Activator.CreateInstance(listType) as IList<T>;
}
}
------其他解决方案--------------------
谢谢您!您的 T 从哪里来的啊
------其他解决方案--------------------
cls<int> list = new cls<int>();
创建的时候告诉的
------其他解决方案--------------------
谢谢!我的 T 是反射动态获取的,请理解一下!
------其他解决方案--------------------
这个意思???
public class Program
{
static void Main(string[] args)
{
var str = "123";
var t = typeof(cls).GetMethod("GetList").MakeGenericMethod(str.GetType()).Invoke(null, new object[] { dt });
Console.ReadLine();
}
}
public class cls
从动态创建的类,再创建Ilist<动态类> 的集合,该怎么创建?
Type t = Type.GetType("动态类名");
//不是要这个 object o = Activator.CreateInstance(t);
//而是要这个 IList<t> it = new List<t>();
给个思路也行。
------最佳解决方案--------------------
Type type = Type.GetType("TestDemo.Student");
Type generic = typeof(List<>);
generic = generic.MakeGenericType(new Type[] { type });
var list = Activator.CreateInstance(generic) as IList;
//out put:System.Collections.Generic.List`1[TestDemo.Student]
Console.WriteLine(list);
这个意思么?比如我的例子中最后的list就是一个Student的泛型集合。
------其他解决方案--------------------
public class cls<T>
{
public IList<T> GetList()
{
var listType = typeof(List<>).MakeGenericType(typeof(T));
return Activator.CreateInstance(listType) as IList<T>;
}
}
------其他解决方案--------------------
谢谢您!您的 T 从哪里来的啊
------其他解决方案--------------------
cls<int> list = new cls<int>();
创建的时候告诉的
------其他解决方案--------------------
谢谢!我的 T 是反射动态获取的,请理解一下!
------其他解决方案--------------------
这个意思???
public class Program
{
static void Main(string[] args)
{
var str = "123";
var t = typeof(cls).GetMethod("GetList").MakeGenericMethod(str.GetType()).Invoke(null, new object[] { dt });
Console.ReadLine();
}
}
public class cls