在 C# 中针对类的特定字段禁用/抑制警告 CS0649
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13726743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable/suppress warning CS0649 in C# for a specific field of class
提问by iseeall
I have some fields in a C# class which I initialize using reflection. The compiler shows CS0649 warning for them:
我在 C# 类中有一些字段,我使用反射进行初始化。编译器为他们显示 CS0649 警告:
Field
foo' is never assigned to, and will always have its default valuenull' (CS0649) (Assembly-CSharp)
Field
foo' is never assigned to, and will always have its default valuenull' (CS0649) (Assembly-CSharp)
I'd like to disable the warning for these specific fields only and still let the warning be shown for other classes and other fields of this class. It is possible to disable CS0649 for the whole project, is there anything more fine-grained?
我只想禁用这些特定字段的警告,并且仍然让该类的其他类和其他字段显示警告。可以为整个项目禁用 CS0649,还有更细粒度的吗?
采纳答案by Douglas
You could use #pragma warningto disable and then re-enable particular warnings:
您可以使用#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
}
Refer to Suppressing “is never used” and “is never assigned to” warnings in C#for an expanded answer.
请参阅在 C# 中抑制“从未使用”和“从未分配给”警告以获取扩展答案。
回答by Alexander Bortnik
//disable warning here
#pragma warning disable 0649
//foo field declaration
//restore warning to previous state after
#pragma warning restore 0649
回答by Hamlet Hakobyan
public class YouClass
{
#pragma warning disable 649
string foo;
#pragma warning restore 649
}
回答by BMac
I believe it's worth noting the warning can also be suppressed by using inline initialization. This clutters your code much less.
我相信值得注意的是,也可以通过使用内联初始化来抑制警告。这会减少您的代码的混乱程度。
public class MyClass
{
// field declarations for which to disable warning
private object foo = null;
// rest of class
}
回答by Aggressor
If you want to disable ALL warningsin the project (rather than per script) then do this:
如果要禁用项目中的所有警告(而不是每个脚本),请执行以下操作:
Ceate a text file called mcs.rsp (for editor scripts) in your YOUR_PROJECT_NAME/Assets directory with contents (for example):
在 YOUR_PROJECT_NAME/Assets 目录中创建一个名为 mcs.rsp(用于编辑器脚本)的文本文件,其中包含内容(例如):
-nowarn:0649
-nowarn:0649
(You can change the number to match whatever warning you want)
(您可以更改数字以匹配您想要的任何警告)
Note: This doesn't disable the warnings in the Unity console if you are using Unity (I am still investigating how to remove those)
注意:如果您使用 Unity,这不会禁用 Unity 控制台中的警告(我仍在研究如何删除这些警告)
Here is some Unity documentationwith more information
这是一些包含更多信息的Unity 文档

