C#8:通过null状态静态分析的属性指定属性值的null性



我在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?这个想法是在处理HasCustomCodetrue的实例时,没有关于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))
{
}

最诚挚的问候:(

最新更新