首页 > 代码库 > StyleCop学习笔记——自定义规则

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

本文将简单的一步一步的指导这可能有助于学习如何创建自己的规则
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 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;
		}
	}

}

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在错误警告列表就会显示检测出来的规则验证。如图: