Expression Tree for o?.Value

后端 未结 1 994
礼貌的吻别
礼貌的吻别 2021-01-21 18:03

I\'d like to generate this sentence using Expression trees:

o?.Value

o is an instance of whichever class.

Is there some wa

1条回答
  •  野的像风
    2021-01-21 18:28

    Normally, if you want to know how to construct an expression tree for some expression, you let the C# compiler do it and inspect the result.

    But in this case, it won't work, because "An expression tree lambda may not contain a null propagating operator." But you don't actually need the null propagating operator, you just need something that behaves like one.

    You can do that by creating an expression that looks like this: o == null ? null : o.Value. In code:

    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);
    }
    

    0 讨论(0)
提交回复
热议问题