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

C#中如何标记CreateCompleteBar("x").Foo的返回值不为空?

解决方法

要让编译器识别CreateCompleteBar("x").Foo的返回值不为空,给CreateCompleteBar方法添加[MemberNotNullIfNotNull]特性即可,通过该特性关联参数input和返回对象的Foo属性:

[return: MemberNotNullIfNotNull(nameof(input), nameof(Foo))]
public static Bar CreateCompleteBar(string? input)
{
    return new Bar { Foo = input };
}

这个特性的作用很明确:当传入的input参数不为空时,返回的Bar对象的Foo属性必然不为空。这样调用CreateCompleteBar("x")时,编译器就能确定返回实例的Foo是非空的,不会再抛出可能为空的警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:39:50