【IT168技术文档】
今天无意中看到这一篇文章Linq beyond queries: strong-typed reflection,发现Linq除了查询还可以用于其它方面,这篇文章里面主要介绍了如何通过Linq来实现强类型的反射。
通常在使用反射的时候,如果不小心把方法名称写错或者参数类型不匹配,运行时就会抛出异常。一般来说我们会这样写代码来获得MethodInfo:
如果对MyTest类进行重构,改变了方法的名称或者参数类型等,运行时肯定会出现异常,因为这些错误在编译期间是检查不出来的。如果项目中大量使用了反射,无疑一点改动就会引发潜在的问题。现在出现了Linq,通过Lambda表达式树可以实现强类型反射。下面是我仿照它的例子写的测试代码,因为现在的API有了一些改动,具体的介绍可以看原文:MethodInfo mi = typeof(MyTest).GetMethod("TestFunc",new Type[]{ typeof(string), typeof(int)});
public class MyReflection { public delegate void Operation<T>(T declaringType); public delegate void Operation<T, A1, A2>(T declaringType, object a1, object a2); public delegate object OperationWithReturnValue<T>(T declaringType); public static MethodInfo Method<T>(Expression<Operation<T>> method) { return GetMethodInfo(method); } public static MethodInfo Method<T>(Expression<OperationWithReturnValue<T>> method) { return GetMethodInfo(method); } public static MethodInfo Method<T, A1, A2>(Expression<Operation<T, A1, A2>> method) { return GetMethodInfo(method); } private static MethodInfo GetMethodInfo(Expression method) { LambdaExpression lambda = method as LambdaExpression; if (lambda == null) throw new ArgumentNullException(); MethodCallExpression methodExpr = null; if (lambda.Body.NodeType == ExpressionType.Call) methodExpr = lambda.Body as MethodCallExpression; else if (lambda.Body.NodeType == ExpressionType.Convert) methodExpr = ((UnaryExpression)lambda.Body).Operand as MethodCallExpression; if (methodExpr == null) throw new ArgumentException(); return methodExpr.Method; } }