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

C#可空范式下Try...方法替代方案及多条件场景最优写法咨询

可选优化方案如下

方案1:使用模式匹配直接整合到if判断(推荐)

C# 8及以上版本支持is not null模式匹配语法,配合逻辑与的短路执行特性,可以完全实现你的需求,写法非常简洁:

if (boolValue && FindValue(key) is not null value)
    DoSomethingWith(value);
else
    DoSomethingElse();

这种写法保证只有boolValue为true时才会执行FindValue,不会产生多余开销,同时匹配成功时value会被自动推断为非空类型,无需额外空检查或!运算符。
如果有多个前置条件,直接按逻辑叠加即可,可读性远高于嵌套三元表达式:

if (cond1 && cond2 && cond3 && FindValue(key) is not null value)
    DoSomethingWith(value);

方案2:保留Try模式,补充空分析注解

如果你更习惯传统TryXXX方法的写法,只需要引入System.Diagnostics.CodeAnalysis命名空间,给out参数添加[NotNullWhen(true)]注解即可解决原签名的空安全问题:

using System.Diagnostics.CodeAnalysis;

// 优化后的TryFindValue签名
bool TryFindValue(Key key, [NotNullWhen(true)] out Value? value);

添加注解后,编译器会识别到当方法返回true时value一定不为空,无需额外空判断,你原来的代码可以完全复用:

if(boolValue && TryFindValue(key, out var value))
    DoSomethingWith(value);
else
    DoSomethingElse();

方案3:多条件复杂场景拆分写法

如果前置判断逻辑非常复杂,也可以把赋值和判断拆分,可读性也很好:

Value? value = null;
if (boolValue)
{
    // 此处可添加任意多前置判断逻辑
    value = FindValue(key);
}

if (value != null)
    DoSomethingWith(value);
else
    DoSomethingElse();

内容的提问来源于stack exchange,提问作者Alexander Høst

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:39:02