如何动态分配lambda <expression <delegate>&gt;表达式<delegate> </delegate> </expression <delegate>

时间:2013-03-20 22:15:02

标签: c# lambda expression

我正在尝试制作动态表达式并为其分配lambda。结果,我得到了例外: System.ArgumentException:类型'Test.ItsTrue'的表达式不能用于赋值类型'System.Linq.Expressions.Expression`1 [Test.ItsTrue]'

有什么问题?

public delegate bool ItsTrue();

public class Sample
{
    public Expression<ItsTrue> ItsTrue { get; set; }
}

[TestClass]
public class MyTest
{
    [TestMethod]
    public void TestPropertySetWithExpressionOfDelegate()
    {
        Expression<ItsTrue> itsTrue = () => true;

        // this works at compile time
        new Sample().ItsTrue = itsTrue;

        // this does not work ad runtime
        var new_ = Expression.New(typeof (Sample));

        var result = Expression.Assign(
            Expression.Property(new_, typeof (Sample).GetProperties()[0]), 
            itsTrue);
    }
}

1 个答案:

答案 0 :(得分:1)

Expression.Assign的第二个参数是表示要赋值的表达式。因此,目前您正在有效地尝试为该属性分配ItsTrue。你需要将它包装起来,使它成为一个表达式,通过itsTrueExpression.Quote返回值Expression.Constant。例如:

var result = Expression.Assign(
    Expression.Property(new_, typeof (Sample).GetProperties()[0]), 
    Expression.Constant(itsTrue, typeof(Expression<ItsTrue>)));

或者,您可能想要Expression.Quote - 这实际上取决于您要实现的目标。

相关问题