如何为类的实例定义运算符==
?我这样尝试过:
public bool operator == (Vector anotherVector)
{
return this.CompareTo(anotherVector) == 1 ;
}
但它说:
最佳答案
您需要将该方法标记为static
,并且还必须实现不等于!=
的方法。
public static bool operator ==(Vector currentVector,Vector anotherVector)
{
return currentVector.CompareTo(anotherVector) == 1 ;
}
您必须为两个对象实现
==
。AND为
!=
和
public static bool operator !=(Vector currentVector,Vector anotherVector)
{
return !(currentVector.CompareTo(anotherVector) == 1) ;
}
另请:Guidelines for Overloading Equals() and Operator == (C# Programming Guide)