StyleCop学习笔记——自定义规则

来源:互联网 发布:短作业优先算法 编辑:程序博客网 时间:2024/04/28 22:48
本文将简单的一步一步的指导这可能有助于学习如何创建自己的规则
1、创建一个项目。

Visual Studio创建一个新的类库项目.NET3.5

2、引用两个DLL,StyleCop.dll和StyleCop.Csharp.dll.


3、添加自定义的规则。


MyCustomAnalyzer.cs代码如下:

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 documentsif (doc.RootElement == null || doc.RootElement.Generated)return;// check all class entriesdoc.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 walkingif (element.ElementType != ElementType.Class)return true;// check whether class name contains "a" letterClass 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 filereturn true;}}}

4、添加一个规则的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>

5、构建

将这个项目生成DLL,把MyCustomAnalyzer.dll放到StyleCop根目录下。


6、部署

打开一个我们要测试的项目代码。点击StyleCop Setting设置用我们的MyCoustomRule。


7、点击RunStyleCop在错误警告列表就会显示检测出来的规则验证。如图:


0 0
原创粉丝点击