我在可空上下文中有以下这段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
为真,则保证该代码将返回非null值。
有没有一种方法可以注释这段代码,告诉编译器如果一个参数包含特定的值,则返回可能为null的例程将返回非null值?