53

我在使用反射初始化的 C# 类中有一些字段。编译器为它们显示 CS0649 警告:

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

我只想禁用这些特定字段的警告,并且仍然让警告显示给其他类和此类的其他字段。整个项目都可以禁用CS0649,还有更细粒度的吗?

4

5 回答 5

94

您可以使用#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
}

有关扩展答案,请参阅在 C# 中抑制“从未使用”和“从未分配给”警告。

于 2012-12-05T15:36:04.237 回答
16

我相信值得注意的是,警告也可以通过使用内联初始化来抑制。这使您的代码更加混乱。

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

    // rest of class
}
于 2016-10-28T18:23:24.737 回答
9
//disable warning here
#pragma warning disable 0649

 //foo field declaration

//restore warning to previous state after
#pragma warning restore 0649
于 2012-12-05T15:36:14.923 回答
5
public class YouClass
{
#pragma warning disable 649
    string foo;
#pragma warning restore 649
}
于 2012-12-05T15:39:15.123 回答
1

如果要禁用项目中的所有警告(而不是每个脚本),请执行以下操作:

在 YOUR_PROJECT_NAME/Assets 目录中创建一个名为 mcs.rsp(用于编辑器脚本)的文本文件,其中包含内容(例如):

-警告:0649

(您可以更改数字以匹配您想要的任何警告)

原始答案

注意:如果您使用 Unity,这不会禁用 Unity 控制台中的警告(我仍在研究如何删除这些警告)

这是一些包含更多信息的Unity 文档

于 2019-11-13T17:45:32.987 回答