【发布时间】:2022-11-04 18:42:17
【问题描述】:
我在可为空的上下文中有这个 C# 代码:
public string? GetValue(int key, bool errorIfInvalidKey)
{
string result = <get the value identified by the key argument, or null if not found>;
if (result == null && errorIfInvalidKey) {
throw new InvalidOperationException("Bad key");
} else {
return result;
}
}
如果调用者指定了无效的key,则errorIfInvalidKey 参数指定是返回null 还是抛出异常。所以,如果errorIfInvalidKey 为真,则此代码保证返回非空.
有没有办法注释此代码以告诉编译器如果参数包含特定值,则返回可能为空的例程将返回非空?
【问题讨论】:
-
我不这么认为。我仍然不喜欢可空引用类型的部分原因。
-
引用类型不需要使用可为空的。
-
@TimChang Nullable 引用类型是 C# 8 及更高版本中的新功能,它允许编译器在代码可能访问 null 引用时警告我们。
-
@NineBerry 谢谢我明白了,这个功能让我大开眼界......
标签: c# nullable-reference-types