o?.Value的表达式树 [英] Expression Tree for o?.Value

查看:99
本文介绍了o?.Value的表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

o?.Value

o是任何类的实例.

有什么办法吗?

推荐答案

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

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.

但是在这种情况下,它将不起作用,因为表达式树lambda可能不包含null传播运算符."但是实际上,您不需要null传播运算符,只需要具有类似行为的运算符即可.

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.

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

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

这篇关于o?.Value的表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆