I have a class like this one:
public class Foo
{
public readonly int A = 1;
public readonly int B = 2;
}
When I run VS2010 built in Code Analysis tool, I get 2 identical warnings: that 'field '...' is visible outside of its declaring type, change its accessibility to private and add a property, with the same accessibility as the field has currently, to provide access to it'.
I want to suppress this warning for all fields in my class Foo, but I don't want to mark every field with SuppressMessage attribute like this:
public class Foo
{
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
public readonly int A = 1;
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
public readonly int B = 2;
}
I want to mark all class members, using code like this:
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
public class Foo
{
public readonly int A = 1;
public readonly int B = 2;
}
But this code doesn't work, I still get a code analysis warning. How can I do it correctly?
There is no way to suppress more than 1 message at a time using SuppressMessageAttribute.
As discussion can be found here, but the relevant part is:
You are running into a common misunderstanding about SuppressMessage.
Each time you put a SuppressMessage in a source file, you suppress exactly one problem (one "row" in the grid). Period.
A SuppressMessage may be placed either "near" the violation or at the module-level. Module-level, assembly-level, and global suppression all mean the same thing. By placing at the module-level, you do not suppress multiple instances of the problem at once. You merely get to locate the SuppressMessage in a different place of the code. The main benefit is that you can, for example, collect all the suppressions related to the assembly in a single file (for example, GlobalSuppressions.cs).
When you use a module-level SuppressMessage, you must specify the Target. The Target must match exactly what is reported in the GUI for a violation of the rule.
There is no way to use SuppressMessage to suppress a rule for the entire scope of a class or the entire scope of a namespace.
You can create the CodeAnalysis rules file with a set of rules like:
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="New Rule Set" Description=" " ToolsVersion="10.0">
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis"
RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CA1111" Action="Ignore" />
</Rules>
</RuleSet>
See step by step walkthrough:
来源:https://stackoverflow.com/questions/7092778/vs2010-code-analysis-suppress-message-ca1051donotdeclarevisibleinstancefields