You need to enable JavaScript to run this app. .NET Core如何优雅获取首个非null且非空字符串 替代嵌套if判断
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core如何优雅获取首个非null且非空字符串 替代嵌套if判断

问题解答

C# 原生的空合并运算符??仅会判断值是否为null,无法自动识别空字符串"",所以不能直接满足你同时排除null和空字符串的需求,不过有几种非常简洁的实现方式:


方案1:LINQ 配合过滤(多变量场景最优)

如果需要判断的变量数量较多,可以把所有待判断的字符串按优先级放进集合,过滤掉null和空值后取第一个即可,代码如下:

using System.Linq;

public static void Main(string[] args)
{
    string a = "value";
    string b = null;
    string c = "";
    // 数组顺序就是判断优先级,从左到右依次校验
    var result = new[] {c, b, a}
        .FirstOrDefault(s => !string.IsNullOrEmpty(s))
        ?? throw new System.Exception("所有字符串均为null或空");
}

这种写法的优势是变量再多也只需要往数组里新增元素即可,不需要嵌套判断,维护成本极低。


方案2:自定义扩展方法(调用更直观)

你可以封装一个专门的扩展方法,后续调用就像用运算符一样便捷:

public static class StringExtensions
{
    public static string OrIfEmpty(this string self, string fallback)
    {
        return string.IsNullOrEmpty(self) ? fallback : self;
    }
}

// 调用示例
public static void Main(string[] args)
{
    string a = "value";
    string b = null;
    string c = b;
    
    var result = c.OrIfEmpty(b).OrIfEmpty(a) 
        ?? throw new System.Exception("所有字符串均为null或空");
}

如果需要同时排除空白字符串(比如全是空格的内容),把代码中的string.IsNullOrEmpty替换为string.IsNullOrWhiteSpace即可。


方案3:模式匹配配合三元运算符(无额外依赖的轻量写法)

如果不想引入LINQ或者自定义扩展,也可以直接用模式匹配实现单行判断:

public static void Main(string[] args)
{
    string a = "value";
    string b = null;
    string c = b;
    
    var result = c is {Length:>0} ? c : b is {Length:>0} ? b : a is {Length:>0} ? a 
        : throw new System.Exception("所有字符串均为null或空");
}

{Length:>0}的模式匹配会自动排除null和空字符串,效果和调用string.IsNullOrEmpty完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 23:15:05