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

C#中给类属性赋值时,如何用??运算符同时处理Null和Empty字符串

处理Null和空字符串的属性赋值方案

没问题,你只需要把原有的null检查逻辑扩展到同时覆盖空字符串的情况就行,这里给你几种实用的实现方式:

1. 使用string.IsNullOrEmpty + 三元运算符(最通用)

这是兼容性最好的写法,几乎所有C#版本都支持,直接通过string.IsNullOrEmpty同时判断null和空字符串(""):

Id = string.IsNullOrEmpty(characater.Id) ? System.Guid.NewGuid().ToString() : characater.Id;

string.IsNullOrEmpty会在目标字符串是null或者长度为0时返回true,这时候就生成新的Guid字符串,否则直接使用原Id值。

2. 使用C# 9+模式匹配(更简洁直观)

如果你用的是C# 9及以上版本,可以用模式匹配语法让代码更易读:

Id = characater.Id is null or "" ? System.Guid.NewGuid().ToString() : characater.Id;

这种写法直接把判断条件写得一目了然,不需要额外调用方法,代码更清爽。

3. 封装扩展方法(复用性强)

如果你的代码里经常需要做这类“空值替换”操作,可以封装一个扩展方法,避免重复写判断逻辑:

public static class StringExtensions
{
    public static string OrDefault(this string? str, Func<string> defaultValueFactory)
    {
        // 这里也可以根据需求换成string.IsNullOrWhiteSpace,处理全空白的情况
        return string.IsNullOrEmpty(str) ? defaultValueFactory() : str;
    }
}

使用的时候就非常简洁:

Id = characater.Id.OrDefault(() => System.Guid.NewGuid().ToString());

额外提示

如果还需要处理全空白字符串(比如" "),只需要把上面的string.IsNullOrEmpty换成string.IsNullOrWhiteSpace就行,它会同时判断null、空字符串和仅包含空白字符的字符串。

内容的提问来源于stack exchange,提问作者user1037747

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:51:58