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

如何为Null/空字符串设置默认值?解决空合并运算符失效问题

解决方案

针对你需要同时处理null和空字符串""并设置默认值的需求,以下是几种简洁的实现方案:

1. 扩展方法(推荐,适合多处复用)

封装一个字符串扩展方法,把string.IsNullOrEmpty的判断逻辑封装起来,之后可以像使用??一样简洁调用:

public static class StringExtensions
{
    public static string GetValueOrDefault(this string input, string defaultValue)
    {
        return string.IsNullOrEmpty(input) ? defaultValue : input;
    }
}

使用示例:

string x = "";
string y = x.GetValueOrDefault("Default Value");
Console.WriteLine(y); // 输出 "Default Value"

这个方案只需要定义一次,项目中任何地方都能直接调用,代码最简洁易读。

2. 三元表达式(单行直接写)

如果不想额外定义扩展类,直接用三元运算符结合string.IsNullOrEmpty写一行代码:

string x = "";
string y = string.IsNullOrEmpty(x) ? "Default Value" : x;
Console.WriteLine(y);

3. C# 8.0+ 模式匹配(语法更直观)

利用C# 8.0及以上的模式匹配特性,直接判断null或空字符串:

string x = "";
string y = x is null or "" ? "Default Value" : x;
Console.WriteLine(y);

4. 空合并结合长度判断(简洁但可读性稍弱)

通过空合并把null转为空字符串,再判断长度,也是单行实现:

string x = "";
string y = (x ?? "").Length == 0 ? "Default Value" : x;
// 或者更简洁的写法
string y = x?.Length > 0 ? x : "Default Value";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:01:16