簡體   English   中英

如何在FXCop中添加自定義規則以避免方法中的==運算符

[英]How to Add Custom Rule to FXCop for avoiding == operator inside the method

我想添加一個自定義規則,以避免在類的方法內使用'=='運算符。 例如在下面的方法中,我需要避免使用string.Compare(str1,str2,StringComparison.Ordinal);的 'str1 == str2' 所以我需要檢查這種類型的代碼是否出現在任何方法中

public void StringTest2()
    {
        string str1 = "Hello";
        string str2 = "HELLO";
        if (str1 == str2)
        {
        }
    }

拒絕吧。

字符串==運算符已經執行了序數比較,並且比堅持使用string.Compare更具可讀性。

即使您確實確實希望明顯地比較序數字符串,我還是建議使用string.Equals(string, string, StringComparison)而不是Compare

**The below code checks both the assignment and equal to operator in an assembly**


public override ProblemCollection Check(Member member)
            {
                var method = member as Method;
                if (method == null)
                    return null;
                if (method.Instructions.Count > 0)
                {
                    foreach (var instruction in method.Instructions)
                    {
                        if (instruction != null)
                            if ( instruction.OpCode == OpCode.Ceq)
                            {
                                var resolution = GetResolution(member.Name.Name);
                                var problem = new Problem(resolution, member)
                                                  {
                                                      Certainty = 95,
                                                      FixCategory = FixCategories.Breaking,
                                                      MessageLevel = MessageLevel.Warning
                                                  };
                                Problems.Add(problem);
                            }
                    }
                }
                return base.Problems;
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM