Expression Tree for o?.Value

老子叫甜甜 提交于 2019-12-02 05:33:42

问题


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

o?.Value

o is an instance of whichever class.

Is there some way?


回答1:


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


来源:https://stackoverflow.com/questions/39613615/expression-tree-for-o-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!