微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决C# 8:通过属性为空状态静态分析指定属性值的可空性

我正在 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 ?当使用 CustomCodeHasCustomCode

的实例时,这个想法没有关于 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))
{

}

最好的问候:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。