Reference Type comparison in C#

时光总嘲笑我的痴心妄想 提交于 2019-12-25 05:24:20

问题


I am trying to understand below problem. I want to know why B == A and C == B are false in the following program.

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


回答1:


In .NET, classes are reference types. 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.

When you define Class1 C = A;

  • First, you create two thing. An object called ObjectC and a reference to the object called C.
  • Then you copy reference of A to reference of C. Now, A and C is reference to the same object.

When you use == with reference objects, if they reference to the same objets, it returns true, otherwise return false.

In your case, that's why B == A and C == B returns false, but if you tried with A == C, it returns true.




回答2:


A and B are different objects. 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.




回答3:


You are comparing the references of the two class instances. Since A and B reside at different memory locations their references are not equal. If you want to test class equality you will need to override the Equals() method. 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.




回答4:


References types hold the address in memory. In your case A and B completely point to different addresses. However, C is pointing to the same address as A does since you assign A to C.




回答5:


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.



来源:https://stackoverflow.com/questions/14004817/reference-type-comparison-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!