使用Expression.Block编译的委托继续抛出NullReferenceException

时间:2013-02-13 15:41:44

标签: c# .net .net-4.0 lambda expression

我正在尝试构建一个为给定对象分配多个属性的Expression,但在调用已编译的委托之后,它会继续从lambda体内抛出NullReferenceException

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,但我到底做错了什么?

1 个答案:

答案 0 :(得分:5)

您应该替换

new[] { a, b, c },

new ParameterExpression[] {},

Expression.Block的第二个参数应该定义块范围的变量 - 但是你已经在Expression.Lambda的最后一个参数中提供了参数a,b和c作为函数级参数。