Expression Tree for o?.Value

2019-07-16 07:30发布

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

o?.Value

o is an instance of whichever class.

Is there some way?

1条回答
干净又极端
2楼-- · 2019-07-16 08:04

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);
}
查看更多
登录 后发表回答