我是靠谱客的博主 漂亮书包,最近开发中收集的这篇文章主要介绍Class does not Implement Equals——Code Correctness(代码正确性),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

    系列文章目录:

    使用Fortify进行代码静态分析(系列文章)

 

class does not implement equals(类未能实现Equals方法)

    示例:    

 1 protected void Check_Clicked(Object sender, EventArgs e)
 2 {
 3    for (int i = 0; i < dgList.Items.Count; i++)
 4    {
 5       if (sender.Equals(dgList.Items[i].FindControl("cbxItem")))
 6       {
 7          
 8       }
 9     }
10 }

   

    Fortify提示:

    Equals() is called on an object that does not implement Equals()。 

  在未实现Equals的类上调用Equals()方法。

 

  详细解释: 

    When comparing objects, developers usually want to compare properties of objects. However, calling Equals() on a class (or any super class/interface) that does not explicitly implement Equals() results in a call to the Equals() method inherited from System.Object. Instead of comparing object member fields or other properties, Object.Equals() compares two object instances to see if they are the same. Although there are legitimate uses of Object.Equals(), it is often an indication of buggy code. 

  当比较对象时,开发人员通常想比较的是对象的属性或字段。但是,调用未显式实现Equals()方法的类、超类或者接口,会导致调用从System.Object的继承而来的Equals()方法。Objects.Equals()方法比较是为了比较两个对象是否相同,而不是比较它们的字段或者属性。虽然这种写法是合法的,但通常这也意味着代码Bug 

 

    Fortify错误示例:    

 1 public class AccountGroup
 2 {
 3     private int gid;
 4 
 5     public int Gid
 6     {
 7         get { return gid; }
 8         set { gid = value; }
 9     }
10 }
11 ...
12 public class CompareGroup
13 {
14     public bool compareGroups(AccountGroup group1, AccountGroup group2)
15     {
16         return group1.Equals(group2);//Equals() is not implemented in AccountGroup
17     }
18 }

 

Fortify建议:

     Verify that the use of Object.Equals() is really the method you intend to call. If not, implement an Equals() method or use a different method for comparing objects.

     确保调用Ojbect.Equals()方法确实是你需要调用的,否则,实现Equals()方法来进行对象的比较。

 

 Fortify推荐示例: 

 1 public class AccountGroup
 2 {
 3     private int gid;
 4 
 5     public int Gid
 6     {
 7         get { return gid; }
 8         set { gid = value; }
 9     }
10 
11     public override Boolean Equals(Object obj)
12     {
13         if (obj == null)
14             return false;
15         if (this.GetType() != obj.GetType())
16             return false;
17         AccountGroup other = (AccountGroup)obj;
18         return (gid == other.Gid);
19     }
20 }
21 22 public class CompareGroup
23 {
24     public static bool compareGroups(AccountGroup group1, AccountGroup group2)
25     {
26         return group1.Equals(group2);
27     }
28 }

 

转载于:https://www.cnblogs.com/gudi/p/6625830.html

最后

以上就是漂亮书包为你收集整理的Class does not Implement Equals——Code Correctness(代码正确性)的全部内容,希望文章能够帮你解决Class does not Implement Equals——Code Correctness(代码正确性)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部