您的位置:首页 > 编程语言

代码分析二:泛型方法与反射

2013-12-17 22:11 363 查看
泛型在类型安全,对于值操作的性能,代码的表现力上有极大的意义。

在CSharpInDepth中,有一个结合泛型方法和反射的例子,代码抄了一遍贴上:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace GenericTest20131211
{
class ReflectionTest
{
public static void PrintMethod<T>() where T: class
{
Console.WriteLine(typeof(T));
}
}

class Test_RefelectionTest
{
public static void Test()
{
//通过typeof操作,获取对ReflectionTest这个类的引用
Type classtype = typeof(ReflectionTest);
//有了类的引用,就可以按照方法的名称获取方法的引用
MethodInfo methodInfo = classtype.GetMethod("PrintMethod");
MethodInfo construct;
//恢复一个方法的调用
construct = methodInfo.MakeGenericMethod(typeof(string));
if (construct != null)
construct.Invoke(null, null); //静态方法,无参数,直接调用
}
}
}
结论:一个很标准的映射操作,难能可贵的是,这个Demo演示了对于泛型方法的调用。现在理解的反射,跟非.net环境中调用DLL的一般步骤很相像:获取操作的一个接口,然后按照方法的名称来获取方法的引用,调用方法的时候传递正确的参数即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: