How to build Expression tree in C# to check if string property is just null (no empty checking)

问题描述 投票:0回答:1

我发现如何使用以下方法检查属性是否为 IsNullOrEmpty:

var methodCall = Expression.Call(typeof(string), "IsNullOrEmpty", null, property);

但我只需要检查该属性是否为空。不检查空状态。

有人可以告诉我吗?
谢谢。

StackOverflows 我通过了,但它们不是我的情况并且没有帮助:

结果应该等同于:

class A
{
  public string Text { get; set; }
}

A a = new A();

// this I need to construct with Expressions:  
bool isNull = a.Text == null;

c# string lambda expression
1个回答
0
投票

你应该可以使用

Expression.Equal

var exp = Expression.Equal(theInstance, Expression.Constant(null, typeof(string)));

接下来创建一个

VariableExpression
并为其分配之前的值:

exp = Expression.Assign(
    Expression.Variable(typeof(bool), "isNull"),
    exp);
© www.soinside.com 2019 - 2024. All rights reserved.