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
相关产品推荐
相关产品推荐

