【发布时间】:2022-10-14 22:31:02
【问题描述】:
String 已经可以为空。我们应该使用string? 吗?
例如:
public class ClassA
{
// should we use here?
public void Method(string? name)
{
// should we use here?
var dic = new Dictionary<string,string?>();
// logic here
}
}
重构工具进行了这些更改。
【问题讨论】:
-
……反对?
-
你为什么要..?
-
“
String已经可以为空”-不,不是(除非您禁用了 NRT)。String不可为空,String?可空。使用String参数时,您还应该添加一个前提条件:if( name is null ) throw new ArgumentNullException(nameof(name));或使用!!,如果您使用的是 .NET 7。 -
您的 .csproj 项目中有
<Nullable>enable</Nullable>吗?