use*_*702 5 c# operator-overloading operators
如何==为我的类的实例定义运算符?我试过这样的:
public bool operator == (Vector anotherVector)
{
return this.CompareTo(anotherVector) == 1 ;
}
Run Code Online (Sandbox Code Playgroud)
但它说:
可以超载的一元运算符
您需要将方法标记为static,并且您必须实现不相等!=.
public static bool operator ==(Vector currentVector,Vector anotherVector)
{
return currentVector.CompareTo(anotherVector) == 1 ;
}
Run Code Online (Sandbox Code Playgroud)
您必须实现==两个对象.
并为 !=
和
public static bool operator !=(Vector currentVector,Vector anotherVector)
{
return !(currentVector.CompareTo(anotherVector) == 1) ;
}
Run Code Online (Sandbox Code Playgroud)
重载的operator ==实现不应该抛出异常.任何重载operator ==的类型也应该重载operator!=.