泛型反射问题总结

1.通过字符串反射带泛型参数的类。 使用字符反撇---键盘1左边的那个键。
 Type listType = Type.GetType(“System.Generic.List'1”); //List<T>
 Type dicType = Type.GetType(“System.Generic.Dictionary'2”); //Dictionary<K,V>

2.识别一个class对象在定义时是否被标记有某个Attribute。
 //原始定义
 [MyAttribute]
 class MyClass{}
 //演示代码代码
 object myObj = new MyClass();
 Attribute atb = System.Attribute.GetCustomAttribute //的到该类定义上制定的属性
         ( obmyObj.GetType, typeof(MyAttribute),false );
         //或者直接获得类定义时的全部属性
         System.Attribute.GetCustomAttributes( obmyObj.GetType);

3。判断一个自定义类的实例是否在别的类中作为proptise时被标记了Attribute
  //原始定义。
  class MyClass{} //自己本身的类定义没有被标记Attribute
  class OtherClass
  {
   [MyAttribute]
   MyClass MyObj; //作为其他类的proptise时被标记了Attribute
  }
 
  演示代码
  OtherClass otherObj = new OtherClass();
  FieldInfo[] fields = otherObj.GetFields(BindingFlags.Public |
            BindingFlags.NonPublic | BindingFlags.Instance);
  foreach (FieldInfo field in fields)
  {
    Attribute atb = System.Attribute.GetCustomAttribute(
          field, //这里是关键。一定是field,而不是field.FieldType
          typeof(MyAttribute), false);

    Assert.IsNotNull(atb, "获取MyAttribute失败");
  }

4. 遍历一个未知类型的所有泛型参数定义
  Object dic = new Dictionary<int, string>();
  foreach (Type type in dic.GetType().GetGenericArguments()) //这里是关键 
  {
    Console.WriteLine("\r\nGenericArgumentType: {0}", type);
  }

5。反射创建未知泛型的实例
  //以List<int>为例
  Type classType = typeof(List<>); //List<>也可以也可以扩展为别的地方传来的参数。
  Type genericType = classType.MakeGenericType(typeof(int)); //这里的typeof(int)也可以扩展为别的地方传来的参数。
  object o = Activator.CreateInstance(type);创建实例。 
  //当然了。这个例子是一个泛型参数的例子。 对于不确定泛型个数的,可以首先通过上一个例子(4)
  //先从obj.GetType().GetGenericArguments()获取全部泛型信息后再进行初始化使用。

6。反射得到Array类型中元素的数据类型。
  string[] obj = new string[]; //模拟一个未知的数组
  Type objType = obj.GetType(); //首先得到数组的Type
  Type elementType = objType.GetElementType(); 然后得到数组内部元素的Type
原文地址:https://www.cnblogs.com/beyond100/p/2068449.html