Skip to main content
 首页 » 编程设计

c#之StyleCop 自定义规则 : Method Parameters and Variables

2024年02月23日13powertoolsteam

我是 StyleCop 的新手,我需要为我工作的地方实现自己的编码标准。我正在使用 VS2005,无法调试它。升级到 VS2008/2010 现在不是我们的选择。

我想知道很多事情:

1) 如何识别方法参数?我尝试了以下但不知道去哪里,SDK 文档并不是很有帮助。

  private bool VisitElement(CsElement element, CsElement parentElement, object context) 
        { 
            if (element.ElementType == ElementType.Method) 
            { 
               ... 

2) 我怎样才能发现声明不跟在赋值之后?例.

  int i;  // Wrong, give warning 
  int i = 0; // True usage 

3) 我怎样才能发现一个文档不只包含 1 个命名空间或里面只包含 1 个类,我怎样才能得到它们的标识符(名称)?

正确:

 namespace Hello  
  { 
     class P{ 
 
     } 
  }  

- 错误:

namespace Hi { 
  class C { 
 
  }  
  class E { 
 
  } 
}   
namespace Ho { 
  class D { 
 
  } 
} 

4) 如何找出函数调用并找出去向? (即阻止对特定功能的调用)

请您参考如下方法:

对于 #1,请查看 Microsoft.StyleCop.CSharp.ReadabilityRules.CheckMethodParameters 方法实现(在 Reflector 或 http://stylecop.codeplex.com/SourceControl/changeset/view/64d44becb157#Project%2fSrc%2fAddIns%2fCSharp%2fAnalyzers%2fReadabilityRules.MethodParameters.cs 中)。

对于 #2,类似下面的内容应该可以解决问题:

private bool VisitExpression(Expression expression, Expression parentExpression, Statement parentStatement, CsElement parentElement, object context) 
{ 
    if (expression.ExpressionType == ExpressionType.VariableDeclarator) 
    { 
        VariableDeclaratorExpression declaratorExpression = (VariableDeclaratorExpression)expression; 
        if (declaratorExpression.Initializer == null) 
        { 
            this.AddViolation(parentElement, expression.LineNumber, "YourRule", declaratorExpression.Identifier.Text); 
        } 
    } 
 
    return true; 
} 

现有的 SA1402 (FileMayOnlyContainASingleClass) 和 SA1403 (FileMayOnlyContainASingleNamespace) 规则应该处理#3。如果它们不适用于您的场景,请指定您希望自定义规则以不同方式执行的操作。

#4 应该是 FxCop 规则,而不是 StyleCop 规则,因为它与源代码样式无关。