前言
今天为了程序能写好看一点,一直在纠结怎么指定动态泛型,
但是想想实用性好像不太大,可是把这技术忘掉太可惜XD
还是记录下来,以防忘记
以下程序范例
- cs
12345678910111213141516171819202122232425262728 | public class DynamicGeneric<T> where T : class , new(){ public string Name { get; set; } public void () { Console.WriteLine("Hello"); } public T () { return new T(); } }public class MyClass1{ public string MyProperty { get; set; } public void MyMethod() { Console.WriteLine("I'm Class1 Method"); }} |
执行过程
- cs
1234567891011121314151617181920 大专栏 [C#] 动态指定泛型类型2122232425262728293031323334353637383940 | static void Main(string[] args){ // 效果大概像这样 // var type = typeof(MyClass1); // DynamicGeneric<type> d = new DynamicGeneric<type>(); // 当然,上面这两行是不能跑的,只是要表达将泛型用变量的方式传入 // Step 1: 取得该类Type var genericListType = typeof(DynamicGeneric<>); // Step 2: 指定泛型类型 var specificListType = genericListType.MakeGenericType(typeof(MyClass1)); // Step 3: 建立Instance object instance = Activator.CreateInstance(specificListType); /*------------------这样就动态指定泛型完成了------------------*/ // 因为回传的对象是object,除非转型才能用强行别的方式操作 // 不然就得用反射方法(Reflection),来操作方法或属性 Type instanceType = instance.GetType(); // 取得属性值 string name = instanceType.InvokeMember( "Name", // 属性名称 System.Reflection.BindingFlags.GetProperty, // 执行取得属性 null, instance, null ) as string; // 执行方法 instanceType.InvokeMember( "SayHello",//方法名称 BindingFlags.InvokeMethod, // 执行调用方法 null, instance, null ); // output : Hello} |
参考数据
stackoverflow dotblogs msdn来源:https://www.cnblogs.com/lijianming180/p/12014282.html