Equals示例中出错 [英] Error in example for Equals

查看:65
本文介绍了Equals示例中出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是MSDN页面中的示例代码:

Here's sample code from the MSDN page :

https://msdn.microsoft.com/en-us/library/bsc2ak47(v = vs.110)。 aspx#备注

https://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx#Remarks

public struct Example
{
   public static void Main()
   {
      Person person1 = new Person("John");
      Person person2 = new Person("John");

      Console.WriteLine("Calling Equals:"); 
      Console.WriteLine(person1.Equals(person2)); 

      Console.WriteLine("\nCasting to an Object and calling Equals:");
      Console.WriteLine(((object) person1).Equals((object) person2));  
   }
}
// The example displays the following output:
//       Calling Equals:
//       True ======================== !!!!!! should this be false?
//   

我运行了这段代码,我得到了是的,不是如所指出的那样真实。 这两个对象有不同的引用...因此结果是错误的。 

I ran this code and I get false, not true as indicated.  The two objects have different references... hence the result is false. 

如该页面上的前一个例子中所述。

As stated in a previous example on that page.

哪个是正确的?

推荐答案

在这种情况下,没有表明你应该成功。 

There is not indicated that you should get true in this situation. 

您正在比较对象的引用,这是不一样的。在示例中表示当您进行比较(参考比较)时它将是相同的: 

You are comparing the reference of the object, that is not the same. In the sample is indicated that it would be the same when you do the compare for (reference compare): 

 Person person1a = new Person("John");
      Person person1b = person1a;

或(价值比较)

  Console.WriteLine(((object) person1.Name).Equals((object) person2.Name)); 


这篇关于Equals示例中出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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