c# null 属性
   // 函数执行完成后,Name属性不为null
    [MemberNotNull(nameof(Name))]
    private void Initialize1()
    {
    }

    // 函数执行完成并返回  true 后,Name属性不为null
    [MemberNotNullWhen(true, nameof(Name))]
    private bool Initialize2() => true;
    // 当返回值为 true 时, 返回 name 不为空
    bool TryGetName([NotNullWhen(true)] out string? name)
    {
        name = this.Name;
        return name != null;
    }

  private string message;

    // 表示可能会用 null 赋值, 但是返回值确定非 null
    // 比如  emp.Message = null; 代码后编译器会认为  Message 可能为 null  
    [AllowNull]
    public string Message
    {
        get => this.message;
        set => this.message = value ?? "test";
    }

    private string? _errorMessage;

    // 表示不允许给属性赋值为 null
    [DisallowNull]
    public string? ErrorMessage
    {
        get => this._errorMessage;
        set => this._errorMessage = value ?? throw new NullException("我是测试");

    }

    // 表示返传入非 null 参数时,返回非 null值 
    [return: NotNullIfNotNull(nameof(key))]
    public string? GetCache(string? key)
    {
        return key == null ? null : "value";
    }
    // NotNull 告诉编译器,运行此函数后,参数 value 不为 null
    static void ThrowIfNull([NotNull] object? value, string errorMessage = "")
    {
        if (value == null)
        {
            throw new ArgumentNullException(errorMessage);
        }
    }

    // DoesNotReturn 告诉编译器此函数不会返回,编译器不要操心后面的代码
    [DoesNotReturn]
    static void ThrowException(string errorMessage)
    {
        throw new Exception(errorMessage);
    }

    // DoesNotReturn 选择编译器 condition == true 后此函数不会返回,编译器不要操心后面的代码
    static void ThrowExceptionIf([DoesNotReturnIf(true)] bool condition, string errorMessage)
    {
        if (condition)
        {
            throw new Exception(errorMessage);
        }
    }

利用C#近几个版本的新特性来辅助编译器的空引用检查
https://www.bilibili.com/video/BV1iQskevEi
官方文档:https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/attributes/nullable-analysis
吕毅的博客:https://blog.walterlv.com/post/csharp-nullable-analysis-attributes.html

上一篇
下一篇