系列文章目录:
class does not implement equals(类未能实现Equals方法)
示例:
protected void Check_Clicked(Object sender, EventArgs e)
{
for (int i = ; i < dgList.Items.Count; i++)
{
if (sender.Equals(dgList.Items[i].FindControl("cbxItem")))
{ }
}
}
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错误示例:
public class AccountGroup
{
private int gid; public int Gid
{
get { return gid; }
set { gid = value; }
}
}
...
public class CompareGroup
{
public bool compareGroups(AccountGroup group1, AccountGroup group2)
{
return group1.Equals(group2);//Equals() is not implemented in AccountGroup
}
}
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推荐示例:
public class AccountGroup
{
private int gid; public int Gid
{
get { return gid; }
set { gid = value; }
} public override Boolean Equals(Object obj)
{
if (obj == null)
return false;
if (this.GetType() != obj.GetType())
return false;
AccountGroup other = (AccountGroup)obj;
return (gid == other.Gid);
}
}
public class CompareGroup
{
public static bool compareGroups(AccountGroup group1, AccountGroup group2)
{
return group1.Equals(group2);
}
}