C# 如何检查输出参数的可空性?

问题描述

我目前正在 .NET 5 (C# 9.0) 中试验 C# 8.0 的可为空引用类型功能,我注意到编译器正确地检查了 TryParseTryGetValue 中 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 (将#修改为@)