0

我正在尝试构建一个将多个属性分配给给定对象的表达式,但是在调用编译的委托之后,它不断NullReferenceException从 lambda 的主体中抛出一个:

var a = Expression.Parameter(typeof(A), "a");
var b = Expression.Parameter(typeof(B), "b");
var c = Expression.Parameter(typeof(C), "c");

LabelTarget returnTarget = Expression.Label(typeof(A));
GotoExpression returnExpression =
    Expression.Return(returnTarget, a, typeof(A));
LabelExpression returnLabel = Expression.Label(
    returnTarget, Expression.Constant(null, typeof(A)));

var expression = Expression.Lambda<Func<A, B, C, A>>(
    Expression.Block(
        typeof(A),
        new[] { a, b, c },
        Expression.Assign(
            Expression.Property(a, typeof(A).GetProperty("B")),
            b),
        Expression.Assign(
            Expression.Property(a, typeof(A).GetProperty("C")),
            c),
        returnExpression,
        returnLabel
    ), 
    a, b, c);

Func<A, B, C, A> func = expression.Compile();

// Calling func throws a NullReferenceException
A result = func(new A(), new B(), new C());

我假设我Expression.Block写错了,但我到底在做什么错呢?

4

1 回答 1

5

你应该换行

new[] { a, b, c },

new ParameterExpression[] {},

的第二个参数Expression.Block应该定义块范围的变量 - 但您已经在Expression.Lambda.

于 2013-02-13T17:13:52.130 回答