c# - o?.Value 的表达式树

标签 c# linq linq-expressions null-propagation-operator

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

o?.Value

o 是任何类的实例。

有什么办法吗?

最佳答案

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

但在这种情况下,它不起作用,因为“表达式树 lambda 可能不包含空传播运算符。”但您实际上并不需要空传播运算符,您只需要一些行为类似的东西。

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

关于c# - o?.Value 的表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39613615/

相关文章:

c# - 中位数 c# 错误计算

c# - WebAPI 2 中的 DefaultInlineConstraintResolver 错误

c# - 如何比较两个 `List<MyObject1> with List<MyObject2>` ?

c# - 如何根据预定义的序列对 IEnumerable 进行排序?

LinqToSQl 和 Member 访问在类型异常上不合法

c# - 有没有办法在表达式树中设置 'DeclaringType'?

c# - 如何将多个 Linq 表达式的结果组合成一个表达式?

c# - InlineKeyboardButton 在 InlineKeyboardMarkup 中有限制吗? Telegram Bot C#

c# - 如何为 IEnumerable.Any 编写 Linq.Expression

c# - 回收调用Application_Start吗?