我刚刚在我的.net core 3.1项目中启用了null检查。
问题是,我有一个响应类
public class DecryptResponse
{
public DecryptStatus Status { get; set; }
//This is the attribute in question
[NotNullWhen(Status==DecryptStatus.Ok)]
public Stream? Stream { get; set; }
public string? ErrorMessage { get; set; }
}
public enum DecryptStatus
{
Ok,
InvalidData,
KeyChecksumFailure,
NoData,
UnhandledError
}
以上是在这种情况下使用的。Verify
方法不允许有空值。
但我知道流不是空的,因为 DecryptStatus==Ok
if (decryptResponse.Status != DecryptStatus.Ok)
return (decryptResponse, null);
var verifyResponse = Verify(customerId, decryptResponse.Stream);
return (decryptResponse, verifyResponse);
是否有任何标签允许这种逻辑,还是需要重写代码?
NotNullWhenAttribute
只用于带参数的使用。它告诉编译器,当方法返回指定值(true或false)时,(out)参数不是空的。例如,当方法返回指定的值(true或false)时,它告诉编译器(out)参数不是空的。
public bool TryParse(string s, [NotNullWhen(true)] out Person person);
这意味着 person
当方法返回时不会为空 true
.
但这个属性并不适合你想要实现的目标。
但你可以尝试使用方法来代替
public bool TryDecrypt(Foo bar,
[NotNullWhen(false) out DecryptError error, // wraps error status & message
[NotNullWhen(true)] out Stream stream)
或者使用null-forgiving操作符
if (decryptResponse.Status == DecryptStatus.Ok)
{
// decryptResponse.Stream!
}