You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中构建表达式树仅检查字符串属性是否为null(不含空值检查)

问题

我已经知道如何用以下代码通过表达式树检查字符串属性是否为NullOrEmpty:

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

但我现在只需要检查属性是否为null,不需要判断空字符串的情况。请问该怎么实现?

我参考过一些相关内容,但都不符合需求,没帮上忙。我想要实现的效果等价于以下代码的逻辑:

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

A a = new A();

// 需用表达式树构建此逻辑:  
bool isNull = a.Text == null;
解决方案

要构建等价于属性 == null的表达式树,直接使用Expression.Equal方法,将目标属性的表达式与代表null的常量表达式做比较即可:

// 假设property是你已有的属性表达式实例
var nullCheckExpression = Expression.Equal(property, Expression.Constant(null, property.Type));

完整可运行示例

如果要把这个逻辑封装成可执行的Lambda表达式,完整代码如下:

using System;
using System.Linq.Expressions;

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

class Program
{
    static void Main()
    {
        // 定义参数:代表A类型的实例
        ParameterExpression param = Expression.Parameter(typeof(A), "a");
        // 获取属性表达式:a.Text
        MemberExpression propertyExpr = Expression.Property(param, "Text");
        // 构建null检查表达式:a.Text == null
        BinaryExpression nullCheck = Expression.Equal(propertyExpr, Expression.Constant(null, propertyExpr.Type));
        // 构建Lambda表达式并编译
        Func<A, bool> checkIsNull = Expression.Lambda<Func<A, bool>>(nullCheck, param).Compile();

        // 测试
        A aWithNull = new A { Text = null };
        A aWithEmpty = new A { Text = "" };
        A aWithValue = new A { Text = "hello" };

        Console.WriteLine(checkIsNull(aWithNull));  // 输出: True
        Console.WriteLine(checkIsNull(aWithEmpty)); // 输出: False
        Console.WriteLine(checkIsNull(aWithValue)); // 输出: False
    }
}

这种方式只做null的比较,完全不会涉及空字符串的判断,正好满足你的需求。

内容的提问来源于stack exchange,提问作者Jan Pokorný

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:57:28