This question already has an answer here:
Expression Tree for o?.Value
                                
                                    (1个答案)
                                
                        
                                5个月前关闭。
            
                    
我正在尝试在表达式树中构建等效于“?”的文件。操作员。

var member = Expression.Property(Expression.Property("PropertyObjectName", value.Property),
    "PropertyOfObject");


这是:member.PropertyObjectName.PropertyOfObject如果Null exception是我要避免的,当然会抛出PropertyObjectName

除了放置null之外,还有什么方法可以构建member?.PropertyObjectName?.PropertyOfObject吗?

最佳答案

您可以使用我的扩展方法

public static class ExpressionExtensions
    {
        public static Expression ElvisOperator(this Expression expression, string propertyOrField)
        {
            return Expression.Condition(Expression.NotEqual(expression, Expression.Constant(null)),
                Expression.PropertyOrField(expression, propertyOrField),
                Expression.Constant(null, expression.Type)
                );
        }
    }


这会产生类似

IIF((x != null), x.propertyname, null)


然后,您可以像这样使用它:

public class TestClass
    {
        public int FirstProp { get; set; }

        public TestClass SecondProp { get; set; }
    }


var variable = Expression.Parameter(typeof(TestClass), "x");
var nullSafe = variable.ElvisOperator("SecondProp");


我做了这个测试:

List<TestClass> tests = new List<TestClass>(){
            new TestClass() { FirstProp = 1, SecondProp = new TestClass() { SecondProp = new TestClass() } },
            new TestClass() { FirstProp = 2 },
            new TestClass() { FirstProp = 3, SecondProp = new TestClass() },
            new TestClass() { FirstProp = 4 },
        };

        var variable = Expression.Parameter(typeof(TestClass), "x");
        var nullSafe = variable.ElvisOperator("SecondProp").ElvisOperator("SecondProp");
        var cond = Expression.NotEqual(nullSafe, Expression.Constant(null, variable.Type));

        var lambda = Expression.Lambda<Func<TestClass, bool>>(cond, new ParameterExpression[] { variable });

        tests = tests.AsQueryable().Where(lambda).ToList();

        Console.WriteLine(tests.Count);


这会在控制台上打印1,因为这样过滤列表:

.Where(x => x.SecondProp?SecondProp != null)

关于c# - 表达式树C#-空条件运算符(?。),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56983701/

10-10 18:19