读书人

C# 反射怎么取自定义类型的Listlt;gt;列表

发布时间: 2012-11-06 14:07:00 作者: rapoo

C# 反射如何取自定义类型的List<>列表的 Type 类型
代码如下:

Assembly asmPlugIn = Assembly.LoadFrom(strPlugInPath);

string strtype = "userInfo";

//这里可以取到自定义类型(自己声明的类userInfo)的Type
Type itemType = asmPlugIn.GetType(strType);


//用这种方法取到的值为 null (这里要取的是list<userInfo> 列表)
Type valueType = asmPlugIn.GetType(string.Format("System.Collections.Generic.List`1[[{0},{1}]]"
, itemType.Name, asmPlugIn.FullName));
//用这种方法取到的值也为 null
Type valueType2 = Type.GetType(string.Format("System.Collections.Generic.List`1[[{0},{1}]]"
, itemType.Name, asmPlugIn.FullName));

[解决办法]
都知道是 List<UserInfo> 了,还反射什么呢?

typeof(List<UserInfo>) 不行吗?
[解决办法]
typeof(List<>)
[解决办法]
Type valueType2 = Type.GetType(string.Format("System.Collections.Generic.List`1[[{0},{1}]]", itemType.Name, asmPlugIn.FullName));

没有加命名空间吧。

itemType.Name 改为 itemType.FullName
[解决办法]
获取List<T>中T的类型

C# code
        public class MyClass        {        }        Type t = typeof(List<MyClass>).GetGenericArguments()[0];        Console.WriteLine(t.Name);        //输出         //MyClass
[解决办法]
是这样的,反射是运行时获取或生成对象,方法和属性,如果你有了你的自定义的对象名,然后想通过字符串在运行时获取对象,那就用反射,否则没有什么意义。
[解决办法]
C# code
        public static object CreateGeneric(Type generic, Type innerType, params object[] args)        {            Type specificType = generic.MakeGenericType(new System.Type[] { innerType });            return Activator.CreateInstance(specificType, args);        }        object genericList = CreateGeneric(typeof(List<>), typeof(EC)); 

读书人网 >C#

热点推荐