如何解决C# 如何检查输出参数的可空性?
我目前正在 .NET 5 (C# 9.0) 中试验 C# 8.0 的可为空引用类型功能,我注意到编译器正确地检查了 TryParse
和 TryGetValue
中 out 参数的可为空性。例如:
var dict = new Dictionary<int,SomeClass>()
if (!dict.TryGetValue(key,out SomeClass? result))
dontUseValue(result); // C# annotates this with: 'result' may be null here
useValue(result); // C# annotates this with: 'result' is not null here
虽然这对于这个特定的类当然是正确的(并尝试获取模式)C# 如何推断这个信息,只有当返回值为真时,结果才为非空?
例如,如果我要使用具有一些自己功能的 TryGetValue 函数创建自己的类,我如何告诉编译器何时 out 参数将不为空?
class DictionaryLike<TRes> where TRes : class,new() {
public bool TryGetValue<TRes>(int key,out TRes? result) {
if (predicate(key)) { result = null; return true; }
result = new TRes(); return false;
// How do I tell C# that the behaviour is inverted?
}
}
对不起,如果这是一个愚蠢的问题,但我真的不明白为什么 Try 模式有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。