Welcome

首页 / 软件开发 / LINQ / 使用Linq实现强类型反射

使用Linq实现强类型反射2011-08-20 博客园 紫色阴影今天无意中看到这一篇文章Linq beyond queries: strong-typed reflection,发现Linq除了查询还 可以用于其它方面,这篇文章里面主要介绍了如何通过Linq来实现强类型的反射。

通常在使用反射的时候,如果不小心把方法名称写错或者参数类型不匹配,运行时就会抛出异常。一 般来说我们会这样写代码来获得MethodInfo:

MethodInfo mi = typeof(MyTest).GetMethod("TestFunc",new Type[]{ typeof (string), typeof(int)});

如果对MyTest类进行重构,改变了方法的名称或者参数类型等,运行时肯定会出现异常,因为这些错 误在编译期间是检查不出来的。如果项目中大量使用了反射,无疑一点改动就会引发潜在的问题。 现在 出现了Linq,通过Lambda表达式树可以实现强类型反射。下面是我仿照它的例子写的测试代码,因为现 在的API有了一些改动,具体的介绍可以看原文:

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;
}
}