我有以下情况:
public class SomeClass {
// Have some other data members as well
public int i ;
}
public class TestClass {
public bool SomeFunction() {
SomeClass a = new SomeClass();
SomeClass b = new SomeClass();
if (a == b) // this is where I am getting compile error
return true;
return false;
}
public static bool operator==(SomeClass a, SomeClass b) {
if (a.i == b.i)
return true;
// compare some other members as well
return false;
}
}
这可能在C#中实现吗?
感谢您的帮助!
答案 0 :(得分:1)
首先,您无法在return true;
方法上使用void
。
其次,应该将重写操作符应用于宿主类。在您的情况下,在SomeClass
内,而不是在TestClass
内。
第三,当您实施==
覆盖运算符时,您还应该实现!=
。
以下是您的代码,已修订并正在使用:
public class SomeClass
{
// Have some other data members as well
public int i;
public static bool operator ==(SomeClass a, SomeClass b)
{
if (a.i == b.i)
return true;
// compare some other members as well
return false;
}
public static bool operator !=(SomeClass a, SomeClass b)
{
return !(a == b);
}
}
public class TestClass
{
public bool SomeFunction()
{
SomeClass a = new SomeClass();
SomeClass b = new SomeClass();
if (a == b) // this is where I am getting compile error
return true;
return false;
}
}
答案 1 :(得分:1)
不,不可能从不参与操作的类中覆盖操作符。
您可以创建一个实现IEualityComparer<SomeClass>
的类,在某些情况下可以使用它来代替标准比较,例如在字典中:
var x = new Dictionary<SomeClass, string>(new SomeClassEqualityComparer());
如果您只想在自己的类中使用比较,可以将其设为常规静态方法,而不是覆盖运算符:
public static bool SomeClassEqual(SomeClass a, SomeClass b) {
if (a.i == b.i) {
return true;
}
// compare some other members as well
return false;
}
用法:
if (SomeClassEqual(a, b))