c# - 在处理不可为空类型的空值的 setter 上停止 C# 警告 "Possible Null Reference Assignment"

标签 c# null compiler-warnings

public class Example
{
    public string Name
    {
        get => m_name;
        set => m_name = value ?? string.Empty; // valid to assign null cause it's handled but caused warnings
    }
    private string m_name;

    public Example(string? name)
    {
        Name = name; // CS8601 - Possible null reference assignment.
    }
}

// imagine this is setting on an instance and not the type
Example.Name = data; // CS8601 - Possible null reference assignment.

在代码中,我有一个 string 类型,它永远不会为 null,因为属性 setter 会将 null 赋值转换为默认值。编译器不理解这一点并且对此提示不已。

我知道我可以通过以下方式修复其中一些问题:

  • ! 放在赋值之后,因为我比编译器更了解 - 不喜欢这样,因为它可能会因重构而中断
  • 在构造函数中分配支持字段而不是属性 - 可以工作,但会重复构造函数中的回退代码,并且再次意味着如果重构/更改,则必须更新多个位置
  • Name 类型更改为 string? - 在这些情况下有效,但会向尝试获取值的所有位置添加编译器警告,这可能不仅仅是设置属性!

有没有一种方法可以修复此警告而不是 hacky?

例如,告诉 setter 赋值可以为 null 或添加与 [MaybeNullWhen(false)] 样式相同的属性,您可以在 上使用>TryGet 方法?

我找不到不涉及代码重复或忽略编译器的问题的解决方法

最佳答案

这是 AllowNullAttribute 的用例。文档 here显示了非常相似的情况。

你只需要做:

using System.Diagnostics.CodeAnalysis;

// ...

[AllowNull]
public string Name
{
    get => m_name;
    set => m_name = value ?? string.Empty;
}

然后您可以为此属性分配可为 null 的类型。

如果您在构造函数中设置属性而不是字段,则还应该使用 MemberNotNullAttribute 标记 setter,以便静态分析器可以看到您已初始化了构造函数。

[MemberNotNull("m_name")]
set => m_name = value ?? string.Empty;

关于c# - 在处理不可为空类型的空值的 setter 上停止 C# 警告 "Possible Null Reference Assignment",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75533008/

相关文章:

c# - 将 C# lambda 函数转换为 VB.net

c# - 如何将文件的值持久存储在目录中?

c# - 在 Sharpdevelop 3.x 中使用 AvalonEdit

python - 如果 "null=True",存储在 DB 中,是 "NULL"还是 "empty values"?

java - 需要使用泛型将列表过滤到特定的子类

c++ - C/C++ : How to use the do-while(0); construct without compiler warnings like C4127?

c# - 如何在 C# 中创建多个对象?

c# - 将空值插入整数列

android - Kotlin !!运算符使用使代码不清晰

ios - Xcode 警告 : Ignoring file libxml2. 2.dylib,为不受支持的文件格式构建,这不是被链接的体系结构