2

我想使用表达式树生成这个句子:

o?.Value

o是任何类的实例。

有什么办法吗?

4

1 回答 1

9

通常,如果您想知道如何为某个表达式构建表达式树,您可以让 C# 编译器完成并检查结果。

但在这种情况下,它不起作用,因为“表达式树 lambda 可能不包含空传播运算符。” 但是您实际上并不需要空传播运算符,您只需要行为类似的东西。

您可以通过创建如下所示的表达式来做到这一点o == null ? null : o.Value:在代码中:

public Expression CreateNullPropagationExpression(Expression o, string property)
{
    Expression propertyAccess = Expression.Property(o, property);

    var propertyType = propertyAccess.Type;

    if (propertyType.IsValueType && Nullable.GetUnderlyingType(propertyType) == null)
        propertyAccess = Expression.Convert(
            propertyAccess, typeof(Nullable<>).MakeGenericType(propertyType));

    var nullResult = Expression.Default(propertyAccess.Type);

    var condition = Expression.Equal(o, Expression.Constant(null, o.Type));

    return Expression.Condition(condition, nullResult, propertyAccess);
}
于 2016-09-21T13:05:38.587 回答