本文介绍了LinqKit System.InvalidCastException当调用方法提供的前pression的成员属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个简单的父/子类结构。我想用linqkit到父应用子拉姆达前pression。我也想通过一个实用的方法来提供拉姆达前pression。

 公共类Foo
{
    公共酒吧酒吧{搞定;组; }
}公共类酒吧
{
    公共字符串值{获得;组; }
    公共静态防爆pression<&Func键LT;酒吧,布尔>> GetLambdaX()
    {
        返回C => c.Value ==A;
    }
}
...防爆pression<&Func键LT;富,布尔>> LX = C => 。Bar.GetLambdaX()调用(c.Bar);
Console.WriteLine(lx.Expand());

以上code抛出

  System.InvalidCastException:无法投类型的对象
System.Linq.Ex pressions.MethodCallEx pression到类型
System.Linq.Ex pressions.LambdaEx pression。
在LinqKit.Ex pressionExpander.VisitMethodCall(MethodCallEx pression米)
在LinqKit.Ex pressionVisitor.Visit(前pression EXP)
在LinqKit.Ex pressionVisitor.VisitLambda(LambdaEx pression拉姆达)
在LinqKit.Ex pressionVisitor.Visit(前pression EXP)
在LinqKit.Extensions.Expand< TDelegate>(防爆pression`1表达式)


解决方案

  VAR lambdaX = Bar.GetLambdaX();防爆pression<&Func键LT;富,布尔>> LX = C => lambdaX.Invoke(c.Bar);

这工作。

小心写

 防爆pression<&Func键LT;富,布尔>> LX = ...

分配编译器处理该行之前和你的情况创建了一个方法调用前pression(即调用Bar.GetLambdaX())分配给LX。

如果您使用VAR ...然后Bar.GetLambdaX();叫和分配,其值(这是拉姆达前pression)在LX = ...

稍后用于

Given a simple parent/child class structure. I want to use linqkit to apply a child lambda expression on the parent. I also want the Lambda expression to be provided by a utility method.

public class Foo
{
    public Bar Bar { get; set; }
}

public class Bar
{
    public string Value { get; set; }
    public static Expression<Func<Bar, bool>> GetLambdaX()
    {
        return c => c.Value == "A";
    }
}
...

Expression<Func<Foo, bool>> lx = c => Bar.GetLambdaX().Invoke(c.Bar);
Console.WriteLine(lx.Expand());

The above code throws

System.InvalidCastException: Unable to cast object of type 
'System.Linq.Expressions.MethodCallExpression' to type 
'System.Linq.Expressions.LambdaExpression'.
at LinqKit.ExpressionExpander.VisitMethodCall(MethodCallExpression m)
at LinqKit.ExpressionVisitor.Visit(Expression exp)
at LinqKit.ExpressionVisitor.VisitLambda(LambdaExpression lambda)
at LinqKit.ExpressionVisitor.Visit(Expression exp)
at LinqKit.Extensions.Expand<TDelegate>(Expression`1 expr)
解决方案
var lambdaX = Bar.GetLambdaX();

Expression<Func<Foo, bool>> lx = c => lambdaX.Invoke(c.Bar);

This works.

Be careful with writing

Expression<Func<Foo, bool>> lx = ...

Before assignment the compiler processes this line and in your case creates a Method Call Expression (i.e. for calling Bar.GetLambdaX()) that is assigned to lx.

If you use var ... then Bar.GetLambdaX(); is called and assigned, the value of which (which is the lambda expression) is used later in lx = ...

这篇关于LinqKit System.InvalidCastException当调用方法提供的前pression的成员属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 06:50