简体   繁体   English

C#中的引用类型比较

[英]Reference Type comparison in C#

I am trying to understand below problem. 我试图理解下面的问题。 I want to know why B == A and C == B are false in the following program. 我想知道为什么在下面的程序中B == AC == B是假的。

using System;

namespace Mk
{
    public class Class1
    {
        public int i = 10;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 A = new Class1();
            Class1 B = new Class1();
            Class1 C = A;

            Console.WriteLine(B == A);
            Console.WriteLine(C == B);
        }
    }
}

Output: 输出:

False
False

A and B are different objects. A和B是不同的对象。 They are of the same class, but not the same instance. 它们属于同一类,但实例不同。 Just like two people can both be people, but they are not the same person. 就像两个人都可以是人一样,但他们不是同一个人。

You are comparing the references of the two class instances. 您正在比较两个类实例的引用。 Since A and B reside at different memory locations their references are not equal. 由于A和B驻留在不同的存储位置,因此它们的引用不相等。 If you want to test class equality you will need to override the Equals() method. 如果要测试类的相等性,则需要重写Equals()方法。 http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx

In your example if you were to test A == C you would see it return true since they both point to the same location in memory. 在您的示例中,如果要测试A == C您将看到它返回true因为它们都指向内存中的同一位置。

In .NET, classes are reference types . 在.NET中,类是引用类型 Reference types has two thing. 引用类型有两件事。 Object and a reference to object . 对象对对象引用

In your case, A is a reference to the ObjectA , B is a reference to the ObjectB . 在你的情况, A是对一个参考ObjectAB是对一个参考ObjectB

When you define Class1 C = A; 当您定义Class1 C = A;

  • First, you create two thing. 首先,创建两件事。 An object called ObjectC and a reference to the object called C . 一个称为ObjectC的对象和对该对象的引用C。
  • Then you copy reference of A to reference of C . 然后,将A的引用复制到C引用。 Now, A and C is reference to the same object . 现在, A和C引用相同的对象

When you use == with reference objects, if they reference to the same objets, it returns true , otherwise return false . 当对引用对象使用==时,如果它们引用相同的对象,则返回true ,否则返回false

In your case, that's why B == A and C == B returns false , but if you tried with A == C , it returns true . 在您的情况下,这就是B == AC == B返回false ,但是如果您尝试使用A == C ,则返回true

The output is correct as you are trying to compare the reference. 当您尝试比较参考时,输出正确。 Here A and B are different objects and hence they result in false on comparison.A, B all are at different memory locations and hence their references are not equal. 这里的A和B是不同的对象,因此它们在比较时导致错误.A,B都位于不同的存储位置,因此它们的引用不相等。

References types hold the address in memory. 引用类型将地址保存在内存中。 In your case A and B completely point to different addresses. 在您的情况下,A和B完全指向不同的地址。 However, C is pointing to the same address as A does since you assign A to C. 但是,由于您将A分配给C,因此C指向与A相同的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM