本文介绍了C#:默认实现==和=为对象的运营商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是平等operatort默认实现(==和!=)

I'd like to know what is default implementation for equality operatort (== and !=)

是吗?

public static bool operator ==(object obj1, object obj2)
{
    return obj1.Equals(obj2);
}
public static bool operator !=(object obj1, object obj2)
{
    return !obj1.Equals(obj2);
}

所以,我只需要重写equals方法或做我需要重写euality运营商呢?

So I only need to override Equals method or do I need to override euality operators as well ?

推荐答案

没有,这是的没有的是 - 在默认情况下,的引用的被检查的平等。运营商例如 == 没有的遗传多态性,不会的通话的东西多态默认情况下。因此,例如:

No, it's not that - by default, references are checked for equality. Operators such as == are not polymorphic and don't call anything polymorphic by default. So for example:

string x = "Hello";
string y = new String("Hello".ToCharArray());
Console.WriteLine(x == y); // True; uses overloaded operator

object a = x;
object b = y;
Console.WriteLine(a == b); // False; uses default implementation

您不能的覆盖的相等运算符,但你可以的负荷的他们,因为串一样。无论你的应该的是一个不同的问题。我想我的一般的想如果我被重写等于,但并不一定总是如此。

You can't override equality operators, but you can overload them, as string does. Whether or not you should is a different matter. I think I usually would if I were overriding Equals, but not necessarily always.

这篇关于C#:默认实现==和=为对象的运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 22:47