使 ReSharper/Roslyn/Compiler 识别 JsonRequiredAttribute

Make ReSharper/Roslyn/Compiler recognize JsonRequiredAttribute

有时,当您创建 DTO 以反序列化 json 时,您会使用 [JsonRequiredAttribute]:

修饰属性
class Car
{
    [JsonRequired]
    public string Make { get; set; }
}

但是,当您在使用 ReSharper 或 C# 8 时执行此操作时,您会看到以下警告:

Car.cs(30, 19): [CS8618] Non-nullable property 'Make' is uninitialized. Consider declaring the property as nullable.

在一些项目中,我有很多这样的警告,我想知道是否有办法只针对误报抑制它们?我可以完全禁用它们,但我不想这样做。

如果您使用的是 C# 8,则可以使用 Null Forgiving Operator。例如,

public string Make { get; set; } = null!;

来自文档

The postfix ! operator has no runtime effect - it evaluates to the result of the underlying expression. Its only role is to change the null state of the expression, and to limit warnings given on its use.