首先创建了三个delegate,用来委托我们自己定义的方法。这里也可以使用Func,不过Func要求有返回值,不能委托无返回值的方法。代码很简单,有一点值得注意的是ExpressionType.Call表示无返回值的方法,ExpressionType.Convert表示有返回值的方法。
下面是一个测试类:
最后看看怎样使用:public class MyTest { public void TestFunc() { Console.WriteLine("Test Function"); } public static void StaticTestFunc() { Console.WriteLine("Test Static Function"); } public int TestFuncWithReturnValue() { Console.WriteLine("Test function with return value"); return 100; } public void TestFuncWithArgs(string arg1, int arg2) { Console.WriteLine("Test function with arguments [{0},{1}]", arg1, arg2.ToString()); } }
输出结果为:MethodInfo mi = MyReflection.Method<MyTest>(m => m.TestFunc()); mi.Invoke(new MyTest(), null); mi = MyReflection.Method<MyTest>(m => MyTest.StaticTestFunc()); mi.Invoke(null, null); mi = MyReflection.Method<MyTest>(m => m.TestFuncWithReturnValue()); Console.WriteLine("Return value from TestFuncWithReturnValue is {0}", mi.Invoke(new MyTest(), null)); mi = MyReflection.Method<MyTest, object, object>((m, x, y) => m.TestFuncWithArgs((string)x, (int)y)); mi.Invoke(new MyTest(), new object[] { "Argument1", 50 });

使用强类型反射的好处是编译器检查,如果方法签名不匹配就会报错,避免了运行时抛出异常。当然它也有不足,不同的方法签名对应一个相应签名的delegate,而且这样的实现效率很低,因为使用了表达式树等,只能根据需要进行取舍了。