您的位置:首页 > 编程语言 > C#

StyleCop(C#代码检测工具)

2017-03-29 20:37 218 查看
一、StyleCop是微软的一个开源的静态代码分析工具,检查c#代码一致性和编码风格。

二、下载地址 http://stylecop.codeplex.com/releases/view/79972

  默认安装目录:C:\Program Files (x86)\StyleCop 4.7

  自己定义的dll规则也放在这个目录下

三、使用方式:打开VS之后选择一个类或者一个类库右击



RunStyleCop运行结果:



四:编写自己的规则:

1、创建一个类库,

  新建一个MyCustomAnalyzer.cs文件,引用StyleCop.dll和StyleCop.Csharp.dll

  代码如下:

using StyleCop;
using StyleCop.CSharp;

namespace MyCustomRules
{
/// <summary>
/// Custom analyzer for demo purposes.
/// </summary>
[SourceAnalyzer(typeof(CsParser))]
public class MyCustomAnalyzer : SourceAnalyzer
{
/// <summary>
/// Extremely simple analyzer for demo purposes.
/// </summary>
public override void AnalyzeDocument(CodeDocument document)
{
CsDocument doc = (CsDocument)document;

// skipping wrong or auto-generated documents
if (doc.RootElement == null || doc.RootElement.Generated)
return;

// check all class entries
doc.WalkDocument(CheckClasses);
}

/// <summary>
/// Checks whether specified element conforms custom rule CR0001.
/// </summary>
private bool CheckClasses(
CsElement element,
CsElement parentElement,
object context)
{
// if current element is not a class then continue walking
if (element.ElementType != ElementType.Class)
return true;

// check whether class name contains "a" letter
Class classElement = (Class)element;
if (classElement.Declaration.Name.Contains("a"))
{
// add violation
// (note how custom message arguments could be used)
AddViolation(
classElement,
classElement.Location,
"AvoidUsingAInClassNames",
classElement.FriendlyTypeText);
}

// continue walking in order to find all classes in file
return true;
}
}

}


AddViolation方法中的三个参数"AvoidUsingAInClassNames"是自己定义的规则,这个规则就是下文xml中的 Rule Name="AvoidUsingAInClassNames"

2、新建一个和类同名的xml文件

  MyCustomAnalyzer.xml内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<SourceAnalyzer Name="My Custom Rule">
<Description>
Custom rule for demo purposes.
</Description>
<Rules>
<Rule Name="AvoidUsingAInClassNames" CheckId="CR0001">
<Context>不能用A字母</Context>
<Description>Fires when 'a' letter is used in class name.</Description>
</Rule>
</Rules>
</SourceAnalyzer>


  设置该xml文件属性:编译方式为嵌入式 (即编译到dll中),Rules中可以放多个Rule但不要忘了改Name和Id

3、保存并编译

  将这个项目生成DLL,把MyCustomAnalyzer.dll放到StyleCop根目录下。到此自定义规则就完成了。

4、使用自己的规则:

  打开VS之后选择一个类或者一个类库右击,选择 StyleCop Settings设置规则,这里可以看到自己新添的规则。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: