gpt4 book ai didi

c# - 如何覆盖 == 运算符

转载 作者:太空狗 更新时间:2023-10-30 00:05:02 25 4
gpt4 key购买 nike

如何为我的类的实例定义运算符 ==?我试过这样:

public bool operator == (Vector anotherVector)
{
return this.CompareTo(anotherVector) == 1 ;
}

但是它说:

overloadable unary operator expected

最佳答案

您需要将该方法标记为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)

Overloaded operator == implementations should not throw exceptions. Any type that overloads operator == should also overload operator !=.

关于c# - 如何覆盖 == 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20640487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com