[C#] 动态指定泛型类型

前言

今天为了程序能写好看一点,一直在纠结怎么指定动态泛型,

但是想想实用性好像不太大,可是把这技术忘掉太可惜XD

还是记录下来,以防忘记

以下程序范例

  • cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28



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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
大专栏  [C#] 动态指定泛型类型21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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

猜你喜欢

转载自www.cnblogs.com/lijianming180/p/12014282.html
今日推荐