C# 反射建立泛型例項
阿新 • • 發佈:2021-07-16
準備一個泛型類和一個已經有具體型別的屬性
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 vartype = 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 vartest = 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 }
結果