简体   繁体   中英

Is there a way to suppress warnings in C# similar to Java's @SuppressWarnings annotation?

Is there a way to suppress warnings in C# similar to Java's @SuppressWarnings annotation?

Failing that, is there another way to suppress warnings in Visual Studio?

Yes.

For disabling, use :

#pragma warning disable 0169, 0414, anyothernumber

Where the numbers are the identifiers of the warnings that you can read from compiler output.

To reenable the warnings after a particular part of code (which is a good idea) use:

#pragma warning restore 0169, anythingelse

This way you can make the compiler output clean, and keep yourself safe because the warnings will only be suppressed for that particular part of code ( where you made sure you don't need to see them ).

Yes there is you can use the pragma warning annotation like this:

#pragma warning disable 414
//some code that generates a warning
#pragma warning restore 414

omitting the numbers disables and restores all warning codes...

There is. See the MSDN page on how to suppress compiler warnings.

From Visual Studio, go to your project properties, select the build tab, and enter the warning number in the Suppress Warnings field.

From code, to disable specific warnings, you can use the #pragma directive:

public class MyClass
{
  #pragma warning disable 0168
  // code

  // optionally, restore warnings again
  #pragma warning restore 0168
  // more code
}

I highly recommend using the following form

#pragma warning disable 649 // Field 'field' is never assigned to, and will always have its default value 'value'

#pragma warning restore 649

The comment on the first line is taken from the first like of the MSDN documentation for Compiler Warning (level 4) CS0649 . Since warnings are numbered in C#, this is your only reference to what's actually going on in the code when you see a warning disabled. Placing it at the end of the line is the only way to get the reason to show up in the search results window when you do a search in your whole solution for pragma warning .

You can identify the warning numbers by looking in the Output window after building your project. Make sure it says Show output from: Build .

您可以查看#pragma指令: http//msdn.microsoft.com/en-us/library/441722ys(VS.80).aspx

查看VisualStudio中的SuppressMessageAttributehttp//msdn.microsoft.com/en-us/library/ms182068.aspx

I guess you could also try to review the project or solution properties and set your warning level to a lower level or so. Otherwise, the other responses are perhaps better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM