我在ASP.NET核心3.1中使用C#8,并通过csproj属性(csproj文件中的Nullable
标记,值为enable
(启用了可为null的引用类型。
我有一个类似于下面的类:
public sealed class Product
{
// other code is omitted for brevity
public bool HasCustomCode { get; }
// this property is null when HasCustomCode is false
public string? CustomCode { get; }
}
有些产品有自定义代码,有些则没有。对于没有自定义代码的产品,属性CustomCode
返回的值为null
。
是否可以告诉C#编译器,每次属性HasCustomCode
的值是true
时,CustomCode
的值都是而不是null?这个想法是在处理HasCustomCode
是true
的实例时,没有关于CustomCode
属性可为空的警告
请参阅unsafePtr:的答案
您可以引用Nullable包。它的作用与复制粘贴基本相同。认为这是将这些属性备份到.net50之前的sdk的最佳方式。
或者,您可以采取以下方法之一:
|-给您的数据一个有意义的默认值
public sealed class Product
{
public string CustomCode { get; } = String.Empty;
public bool HasCustomCode => CustomCode != String.Empty;
}
|-将可为null的数据重构为私有成员
public sealed class Product
{
private string? customCode;
public bool HasCustomCode => customCode != null;
public string CustomCode => customCode ?? String.Empty;
}
|-使用有意义的提取方法
public sealed class Product
{
private string? customCode;
public bool HasCustomCode(out string customCode)
=> (customCode = this.customCode) != null;
}
if (p.HasCustomCode(out string code))
{
}
最诚挚的问候:(