C# 反射创建泛型实例

准备一个泛型类和一个已经有具体类型的属性

1 public class PropertyClass<T1, T2>
2     {
3     }
4 
5     public class Test
6     {
7         public PropertyClass<string, int> P { get; set; }
8     }

准备一个方法来实例化有具体类型的属性

 1 public static void Instantiationa(object obj, string propertyName)
 2         {
 3             var type = obj.GetType();
 4 
 5             var property = type.GetProperty(propertyName);//获取属性信息
 6 
 7             var t = property.PropertyType;
 8             if (t.IsGenericType)
 9             {
10                 var types = t.GenericTypeArguments;//获取泛型类的真实类型参数
11                 var tm = typeof(PropertyClass<,>);//获取开放泛型
12                 var ttt = tm.MakeGenericType(types);//根据类型参数获取具象泛型
13                 var value = Activator.CreateInstance(ttt);//实例化
14                 property.SetValue(obj, value);//赋值
15             }
16         }

运行

 1 private static void Main(string[] args)
 2         {
 3             var test = new Test();//此处不实例化属性;
 4             if (test.P == null)
 5             {
 6                 Console.WriteLine("属性为空");
 7             }
 8             Instantiationa(test, "P");
 9             if (test.P != null)
10             {
11                 Console.WriteLine("属性已经被实例化");
12             }
13         }

运行结果 

 

再创建一个 实例化具象类型的方法 

在泛型类里面添加2个属性

1 public class PropertyClass<T1, T2>
2     {
3         public T1 Value1 { get; set; } = default;
4 
5         public T2 Value2 { get; set; } = default;
6     }

创建实例化的方法

1  public static object InstantiationaReal()
2         {
3             var type = typeof(PropertyClass<,>);
4             var types = new Type[] { typeof(double), typeof(bool) };//具体类型
5             var trueType = type.MakeGenericType(types);//根据类型参数获取具象泛型
6             var obj = Activator.CreateInstance(trueType);
7             return obj;
8         }

 

运行

 1  private static void Main(string[] args)
 2         {
 3 
 4             var obj = (PropertyClass<double, bool>)InstantiationaReal();
 5 
 6             if (obj!=null)
 7             {
 8                 Console.WriteLine(obj.Value1);
 9                 Console.WriteLine(obj.Value2);
10             }
11             
12         }

结果

 

posted @ 2021-07-16 10:23  只吃肉不喝酒  阅读(811)  评论(0编辑  收藏  举报