StyleCop 自定义规则:public方法的首字母必须大写

StyleCop 版本:4.7.53.0

问题分析

  • SA1300:ElementMustBeginWithUpperCaseLetter 要求元素必须以大写字母开头,其元素包含类名、方法名、属性名等。

  • SA1306:FieldNamesMustBeginWithLowerCaseLetter 要求字段名必须以小写字母开头。

对于窗体文件来说,这两条规则是互相矛盾的。因为窗体控件自动生成的事件是以【变量名_事件名】命名的,如果变量名符合规则,那么控件事件的方法名也将为小写开头,则不符合SA1300。

因此,一种合适的做法是取消SA1300、保留SA1306。另外自定义规则实现 public 方法名的检查。

自定义规则

  • 自定义规则项目的创建及配置方法见 C#静态代码检查工具StyleCode – 自定义规则。下面仅介绍相关代码。

  • CustomAnalyzer.cs

using StyleCop;
using StyleCop.CSharp;

namespace CustomRules
{
    /// <summary>
    /// Custom analyzer for demo purposes. 
    /// </summary>
    [SourceAnalyzer(typeof(CsParser))]
    public class CustomAnalyzer : SourceAnalyzer
    {        
        /// <summary>
        /// Extremely simple analyzer for demo purposes. 
        /// </summary>
        /// <param name="document"></param>
        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 (element.ElementType != ElementType.Method)
                return true;
            // 检查是否为public方法
            if (element.AccessModifier != AccessModifierType.Public)
                return true;

            // 检查方法的首字母是不是大写字母
            Method methodElement = (Method)element;
            string firstLetter = methodElement.Declaration.Name.Substring(0, 1);
            if (firstLetter.ToUpper().Equals(firstLetter) == false)
            {
                // add violation 
                // (note how custom message arguments could be used) 
                AddViolation(
                    methodElement,
                    methodElement.Location,
                    "PublicMethodMustBeginWithUpperCaseLetter",
                    methodElement.FriendlyTypeText);
            }

            // continue walking in order to find all classes in file 
            return true;
        }
    }
}
  • CustomAnalyzer.xml
<?xml version="1.0" encoding="utf-8" ?>
<SourceAnalyzer Name="Custom Rules">
  <Description>
    Custom rules.
  </Description>
  <Rules>
    <Rule Name="PublicMethodMustBeginWithUpperCaseLetter" CheckId="CR0001">
      <Context>Public method must begin with upper case letter.</Context>
      <Description>Public method must begin with upper case letter.</Description>
    </Rule>
  </Rules>
</SourceAnalyzer>

你可能感兴趣的:(custom,StyleCop)