以下(不正确/危险)代码
class EvilClass
{
protected int x;
public EvilClass(int x)
{
this.x = x;
}
public override bool Equals(Object obj)
{
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
{
return false;
}
else
{
EvilClass p = (EvilClass)obj;
p.x = 42;
return (x == p.x);
}
}
public override int GetHashCode()
{
return (x << 2);
}
public override string ToString()
{
return String.Format("EvilClass({0})", x);
}
}
void Main()
{
var e1 = new EvilClass(1);
var e2 = new EvilClass(2);
var equals = e1.Equals(e2);
Console.WriteLine("{0}", e1.ToString());
Console.WriteLine("{0}", e2.ToString());
}
输出:
EvilClass(1)
EvilClass(42)
如您所见,调用修改 e2。如果我们在编译器中将参数标记为不允许您修改它。e1.Equals(e2)
Object.Equals() 不假设要更改它的参数 - 那么为什么参数不在(输入)参数中?
潇潇雨雨
相关分类