问题描述
我正在 ASP.NET core 3.1 中使用 C# 8 和通过 csproj 属性(csproj 文件中的 Nullable
标记,值为 enable
)启用的可为空引用类型。
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
的值为not null ?当使用 CustomCode
为 HasCustomCode
true
属性的可为空性的警告
解决方法
从 unsafePtr 中查看 this answer:
您可以参考 Nullable 包。它的作用与您使用复制粘贴所做的基本相同。认为这是将这些属性反向移植到 .net50 之前的 sdks 的最佳方式。
或者,您可以采用以下方法之一:
|- 给你的数据一个有意义的默认值
public sealed class Product
{
public string CustomCode { get; } = String.Empty;
public bool HasCustomCode => CustomCode != String.Empty;
}
|- 将可空数据重构为私有成员
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))
{
}
最好的问候:)