o?.Value 的表达式树

Expression Tree for o?.Value

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

o?.Value

o 是 class.

的一个实例

有什么办法吗?

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

但在这种情况下,它不起作用,因为 "An expression tree lambda may not contain a null propagating operator." 但您实际上并不需要 null 传播运算符,您只需要一些行为类似于 one 的东西。

您可以通过创建如下所示的表达式来做到这一点: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);
}