C# 如何动态分配lambda<;表达式<;代表>&燃气轮机;表达<;代表>;

C# 如何动态分配lambda<;表达式<;代表>&燃气轮机;表达<;代表>;,c#,lambda,expression,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> It

我正在尝试创建动态表达式并将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);
    }
}
public委托bool itsttrue();
公共类样本
{
公共表达式ItsTrue{get;set;}
}
[测试类]
公共类MyTest
{
[测试方法]
public void TestPropertySetWithExpressionOffelegate()的测试属性
{
表达式itsTrue=()=>true;
//这在编译时起作用
新样本().ItsTrue=ItsTrue;
//这在运行时不起作用
var new=Expression.new(typeof(Sample));
var result=Expression.Assign(
Expression.Property(new,typeof(Sample).GetProperties()[0]),
是的);
}
}

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

var result = Expression.Assign(
    Expression.Property(new_, typeof (Sample).GetProperties()[0]), 
    Expression.Constant(itsTrue, typeof(Expression<ItsTrue>)));
var result=Expression.Assign(
Expression.Property(new,typeof(Sample).GetProperties()[0]),
常量(itsTrue,typeof(表达式));

或者,你可能需要
Expression.Quote
-这取决于你想要实现什么。

谢谢你,乔恩,Expression.Quote正是我所期望的。