【发布时间】:2009-09-04 11:16:51
【问题描述】:
有没有办法在 C# 中抑制警告,类似于 Java 的 @SuppressWarnings 注释?
如果做不到这一点,还有其他方法可以在 Visual Studio 中抑制警告吗?
【问题讨论】:
标签: c# java visual-studio compiler-warnings
有没有办法在 C# 中抑制警告,类似于 Java 的 @SuppressWarnings 注释?
如果做不到这一点,还有其他方法可以在 Visual Studio 中抑制警告吗?
【问题讨论】:
标签: c# java visual-studio compiler-warnings
是的。
要禁用,请使用:
#pragma warning disable 0169, 0414, anyothernumber
其中的数字是您可以从编译器输出中读取的警告标识符。
要在代码的特定部分(这是个好主意)之后重新启用警告:
#pragma warning restore 0169, anythingelse
通过这种方式,您可以使编译器输出干净,并确保自己的安全,因为警告只会在代码的特定部分被抑制(您确保不需要看到它们的地方 )。
【讨论】:
是的,您可以像这样使用编译指示警告注释:
#pragma warning disable 414
//some code that generates a warning
#pragma warning restore 414
省略数字会禁用并恢复所有警告代码...
【讨论】:
有。请参阅MSDN 页面了解如何抑制编译器警告。
在 Visual Studio 中,转到您的项目属性,选择构建选项卡,然后在 Suppress Warnings 字段中输入警告编号。
从代码中,要禁用特定警告,您可以使用#pragma 指令:
public class MyClass
{
#pragma warning disable 0168
// code
// optionally, restore warnings again
#pragma warning restore 0168
// more code
}
【讨论】:
我强烈建议使用以下表格
#pragma warning disable 649 // Field 'field' is never assigned to, and will always have its default value 'value'
#pragma warning restore 649
第一行的注释取自 Compiler Warning (level 4) CS0649 的 MSDN 文档的第一个类似。由于警告在 C# 中编号,因此当您看到禁用警告时,这是您对代码中实际情况的唯一参考。当您在整个解决方案中搜索 pragma warning 时,将其放在行尾是获得在搜索结果窗口中显示原因的唯一方法。
您可以在构建项目后通过查看输出窗口来识别警告编号。确保它显示 Show output from: Build。
【讨论】:
您可以检查#pragma 指令:http://msdn.microsoft.com/en-us/library/441722ys(VS.80).aspx。
【讨论】:
看看 VisualStudio 中的SuppressMessageAttribute:http://msdn.microsoft.com/en-us/library/ms182068.aspx
【讨论】:
您可以使用 SuppressMessage 数据注释来防止警告。
看起来像这样:
[SuppressMessage("Reason #Enter whatever you'd like", "ID, must match what intellsense is showing it looks something like this: IDE0001", Justification = "(optional, your own description")]
这是一个真实的例子:
[SuppressMessage("IntelliSenseCorrection", "IDE0001", Justification = "Do Not Remove <T> Variable, It's Required For Dapper")]
【讨论】:
我想您也可以尝试查看项目或解决方案属性并将您的警告级别设置为较低级别左右。否则,其他响应可能会更好。
【讨论】: