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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值