静态运算符 == 未检测到被高估的方法
我有基类 Class1 和派生类 2。我创建了两个 class2 实例,但定义为 class1。 我的问题是我无法在这些对象之间进行通用比较。 下面是一个例子:
public class Class1
{
public int Property1 = 0;
}
public class Class2 : Class1
{
public int Property2 = 0;
public static bool operator ==(Class2 c1, Class2 c2)
{
return c1.Property2 == c2.Property2;
}
public static bool operator !=(Class2 c1, Class2 c2)
{
return c1.Property2 != c2.Property2;
}
}
public class Class3 : Class1
{
public int Property3 = 0;
}
static void Main(string[] args)
{
Class1 obj1 = new Class2();
Class1 obj2 = new Class2();
if (obj1 == obj2)
{
Console.WriteLine("Yes !!! The two objects are equal!");
}
else
{
Console.WriteLine("The two objects are not equal.");
}
}
如果我更改行:
if (obj1 == obj2)
for:
if ((Class2)obj1 == (Class2)obj2)
一切都正确,但如果 obj1 和 obj2 是 Class3,我会收到错误
如何解决它?
谢谢克兰德尔
I have base class Class1 and a derived class2. I create two instances of class2 but defined as class1.
My problem is I can't do a generic compare between this objects.
Here are an example:
public class Class1
{
public int Property1 = 0;
}
public class Class2 : Class1
{
public int Property2 = 0;
public static bool operator ==(Class2 c1, Class2 c2)
{
return c1.Property2 == c2.Property2;
}
public static bool operator !=(Class2 c1, Class2 c2)
{
return c1.Property2 != c2.Property2;
}
}
public class Class3 : Class1
{
public int Property3 = 0;
}
static void Main(string[] args)
{
Class1 obj1 = new Class2();
Class1 obj2 = new Class2();
if (obj1 == obj2)
{
Console.WriteLine("Yes !!! The two objects are equal!");
}
else
{
Console.WriteLine("The two objects are not equal.");
}
}
if I change the line:
if (obj1 == obj2)
for:
if ((Class2)obj1 == (Class2)obj2)
all is right, but if obj1 and obj2 are Class3 I get error
How can I resolve it ?
Thank you
Crandel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将运算符重载添加到所有类中,在示例中将其添加到 Class1 中以使其正常工作
Add your operator overloads to all the classes, in your example add it to
Class1
as well to get it to work在我看来,重载 == 和 != 运算符根本不是一个好主意,因为引用类型的默认语义是比较引用而不是值。我宁愿重写 bool Equals(System.Object) 和 int GetHashCode() 并使用 Equals 进行值比较 - 恕我直言,通过减少歧义使代码更具可读性。
In my opinion it is a bad idea to overload the == and != operators at all, since there default semantic with reference types is to compare references rather than values. I'd rather override bool Equals(System.Object) and int GetHashCode() and use Equals for value comparison - IMHO makes the code more readable by virtue of reducing ambiguity.