我对引用类型中的内容相等性有点困惑。在这两种情况下,我都没有压倒平等 - 那么为什么行为不同。
请参阅 2 个简单的代码示例:
示例 1:返回 True
class Program
{
static void Main(string[] args)
{
object o1 = "ABC";
object o2 = "ABC";
Console.WriteLine("object1 and object2: {0}", o1.Equals(o2));
}
}
示例 2:两个语句都返回 False
class Program
{
static void Main(string[] args)
{
Person person1 = new Person("John");
Person person2 = new Person("John");
Console.WriteLine("person1 and person2: {0}", person1.Equals(person2));
Console.WriteLine("person1 and person2: {0}", ((object)person1).Equals((object)person2));
Console.ReadLine();
}
}
public class Person
{
private string personName;
public Person(string name)
{
this.personName = name;
}
}