Object.Equals是虚拟的,但是Object.operator ==不在C#中使用它吗? [英] Object.Equals is virtual, but Object.operator== does not use it in C#?

查看:125
本文介绍了Object.Equals是虚拟的,但是Object.operator ==不在C#中使用它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被我不太了解的C#中的一个奇怪的不对称"击中.请参见以下代码:

using System;
using System.Diagnostics;
namespace EqualsExperiment
{
    class Program
    {
        static void Main(string[] args)
        {
            object apple = "apple";
            object orange = string.Format("{0}{1}", "ap", "ple");
            Console.WriteLine("1");
            Debug.Assert(apple.Equals(orange));
            Console.WriteLine("2");
            Debug.Assert(apple == orange);
            Console.WriteLine("3");
        }
    }
}

对于您所有的.NET专家来说,这都是显而易见的,但是第二个断言失败了.

在Java中,我了解到==是这里称为Object.ReferenceEquals的同义词.在C#中,我认为Object.operator ==使用的是Object.Equals,它是虚拟的,因此在System.String类中将其覆盖.

有人可以解释一下,为什么第二个断言在C#中失败?我的哪个假设是错误的?

解决方案

==运算符不是同义词,而是为不同类型定义的运算符.

为字符串定义了==运算符,然后实际上使用了Equals方法:

public static bool operator ==(string a, string b) {
  return Equals(a, b);
}

但是,在代码中,您没有在字符串上使用运算符,而是在对象上使用了运算符,因此得到的是为对象定义的==运算符,该运算符使用ReferenceEquals进行比较.

要使用的运算符的重载是在编译时确定的,所以决定重载的是变量的类型,而不是变量所指向的对象的实际类型.

I got hit by a strange "asymmetry" in C# that I do not really understand. See the following code:

using System;
using System.Diagnostics;
namespace EqualsExperiment
{
    class Program
    {
        static void Main(string[] args)
        {
            object apple = "apple";
            object orange = string.Format("{0}{1}", "ap", "ple");
            Console.WriteLine("1");
            Debug.Assert(apple.Equals(orange));
            Console.WriteLine("2");
            Debug.Assert(apple == orange);
            Console.WriteLine("3");
        }
    }
}

It might be obvious for all you .NET gurus, but the 2nd assert fails.

In Java I have learnt that == is a synonym for something called Object.ReferenceEquals here. In C#, I thought that Object.operator== uses Object.Equals, which is virtual, so it is overriden in the System.String class.

Can someone explain, why does the 2nd assert fail in C#? Which of my assumptions are bad?

解决方案

The == operator is not a synonym, it's an operator that is defined for different types.

The == operator is defined for strings, and then it does actually use the Equals method:

public static bool operator ==(string a, string b) {
  return Equals(a, b);
}

However, in your code you are not using the operator on strings, you are using it on objects, so what you get is the == operator defined for objects, which uses ReferenceEquals to do the comparison.

Which overload of the operator to use is decided at compile time, so it's the type of the variables that decide the overload, not the actual type of the objects that the variables point to.

这篇关于Object.Equals是虚拟的,但是Object.operator ==不在C#中使用它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆