对于特定的类字段,在C#中禁用/禁止警告CS0649

ise*_*all 38 c# suppress-warnings

我在C#类中有一些字段,我使用反射初始化.编译器显示CS0649警告:

Field foo' is never assigned to, and will always have its default valuenull'(CS0649)(Assembly-CSharp)

我想仅禁用这些特定字段的警告,并仍然显示该类的其他类和其他字段的警告.可以为整个项目禁用CS0649,还有更细粒度的东西吗?

Dou*_*las 66

您可以使用#pragma warning禁用然后重新启用特定警告:

public class MyClass
{
    #pragma warning disable 0649

    // field declarations for which to disable warning
    private object foo;

    #pragma warning restore 0649

    // rest of class
}
Run Code Online (Sandbox Code Playgroud)

有关扩展答案,请参阅C#中的抑制"永不使用"和"永不分配"警告.


小智 9

我相信值得注意的是,使用字段初始化程序也可以抑制警告.这会使您的代码更加混乱.

public class MyClass
{
    // field declarations for which to disable warning
    private object foo = null;

    // rest of class
}
Run Code Online (Sandbox Code Playgroud)

  • 另一种方法是使用“default”;`私有对象 foo = 默认;` (2认同)

Ale*_*nik 7

//disable warning here
#pragma warning disable 0649

 //foo field declaration

//restore warning to previous state after
#pragma warning restore 0649
Run Code Online (Sandbox Code Playgroud)


Ham*_*yan 5

public class YouClass
{
#pragma warning disable 649
    string foo;
#pragma warning restore 649
}
Run Code Online (Sandbox Code Playgroud)

  • 他可能只是没有看到第一个答案。不管怎么说,还是要谢谢你:) (6认同)