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

如何编写支持空值的可空类型模式匹配以适配方法重载?

问题描述

需要根据包含可能为空值的object?参数列表,匹配最合适的重载方法并调用。现有代码在参数非空时正常运行,但无法处理空值场景,期望找到更简洁的实现方式,替代复杂的when条件判断。

最优解决方案

方案1:使用C# 9+的联合模式(推荐)

C# 9及以上支持联合模式,可以直接匹配null或目标类型,写法简洁且符合预期:

string TheMethod(string? foo, string? bar);
string TheMethod(string? foo);
List<object?> arguments = [...];

switch (arguments)
{
    case [null or string foo, null or string bar]:
        return TheMethod(foo, bar);
    case [null or string foo]:
        return TheMethod(foo);
}

这里null or string联合模式会匹配所有可以赋值给string?的对象(即null或string实例),变量foo和bar会被自动推断为string?类型,直接满足重载方法的参数要求。

方案2:兼容旧版C#的写法

如果使用C# 8或更早版本,不支持联合模式,可以用when条件配合is string?判断(等价于is null or string):

switch (arguments)
{
    case [var foo, var bar] when foo is string? && bar is string?:
        return TheMethod(foo as string, bar as string);
    case [var foo] when foo is string?:
        return TheMethod(foo as string);
}

这种写法虽然不如联合模式简洁,但避免了复杂的逻辑判断,比手动拆分null和类型的写法更易读。

说明

为什么[string? foo, string? bar]写法不合法?因为模式匹配中的类型模式仅支持非可空值类型或引用类型,string?作为可空引用类型,无法直接作为类型模式使用。而联合模式null or string刚好弥补了这个缺口,完美实现匹配string?类型的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:33:10