-->

Lambda表达式 (Lambda expressions > and MethodInfo

2019-09-21 20:26发布

虽然从迁移到VS2010 VS2012的一个项目,我遇到了以下问题。 该项目使用反射了很多,为了从下面的代码放在一个接口获得的MethodInfo:

Expression<Func<ITest, Func<ServiceRequest, ServiceResponse>>> expression = scv => scv.Get;

UnaryExpression unaryExpression = expression.Body as UnaryExpression;

MethodCallExpression methodCallExpression = unaryExpression.Operand as MethodCallExpression;

ConstantExpression constantExpression = methodCallExpression.Arguments[2] as ConstantExpression;

MethodInfo myMethod = constantExpression.Value as MethodInfo;

这工作得很好用VS2010编译,但methodCallExpression.Arguments.Count()为2,如果代码与VS2012针对.NET 4.0编译。

反编译后,我注意到,编译器对于相同的表达产生不同的代码。

这是一个设计问题,因为设计不应该的“幻数”接力像2号上methodCallExpression.Arguments [2]。 我试图找到这个用以下解决方案:

MethodCallExpression outermostExpression = expression .Body as MethodCallExpression;
MethodInfo myMethod = outermostExpression.Method;

但是outermostExpression为空。

最后,我做了它的工作改变表达如下:

Expression<Func<ITest, ServiceResponse>> expression = scv => scv.Get(default(ServiceRequest));
MethodCallExpression outermostExpression = expression.Body as MethodCallExpression;
Assert.AreEqual("Get", outermostExpression.Method.Name);

这是不理想,但它的工作原理上都VS2010和VS2012。

有没有办法从像下面的表达式找到的MethodInfo:

Expression<Func<ITest, ServiceResponse>> expression = scv => scv.Get(default(ServiceRequest));
MethodInfo methodInfo = GetInnerMethodInfo( expression );
Assert.AreEqual("Get", methodInfo.Name);

Answer 1:

我不知道为什么有在表达式编译的方式不同。 但是,如果你正在寻找中恒委托方法的方法信息,你可以编译表达与ITest实现获得在代表们MethodInfo 。 例如:

Expression<Func<ITest, Func<ServiceRequest, ServiceResponse>>> expression = scv => new Func<ServiceRequest, ServiceResponse>(scv.Get);
Func<ServiceRequest, ServiceResponse> ret = expression.Compile()(new Test());
MethodInfo methodInfo = ret.Method;

..where Test是一些类并实现ITest 。 其中一期工程在2012年和2010。

我不能确定如何可以得到从2012年的表达式方法信息而无需首先编译它...

更新:

如果编译的表达不是一个选项,看来编译器产生不同的表达和使MethodInfoMethodCallExpression.Object属性在C#5的编译器。 您可以检查,看看是否属性不为null ,并使用其值的MethodInfo ,或继续在获取元素Arguments集合。 例如:

Expression<Func<ITest, Func<ServiceRequest, ServiceResponse>>> expression = 
    scv => new Func<ServiceRequest, ServiceResponse>(scv.Get);

UnaryExpression unaryExpression = expression.Body as UnaryExpression;

MethodCallExpression methodCallExpression = 
    unaryExpression.Operand as MethodCallExpression;

ConstantExpression constantExpression = 
    methodCallExpression.Object as ConstantExpression;

MethodInfo methodInfo;
if (constantExpression != null)
{
    methodInfo = constantExpression.Value as MethodInfo;
}
else
{
    constantExpression = methodCallExpression.Arguments
                            .Single(a => a.Type == typeof(MethodInfo) 
                                && a.NodeType == ExpressionType.Constant) as
                            ConstantExpression;
    methodInfo = constantExpression.Value as MethodInfo;
}

我使用LINQ查询以获得在该元件Arguments集合,如果你喜欢硬编码的指数,你很可能使用的是代替。 更完整的错误检查是必要的,也是。



文章来源: Lambda expressions > and MethodInfo