C#中的引用类型比较 [英] Reference Type comparison in C#

查看:259
本文介绍了C#中的引用类型比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解以下问题.我想知道为什么在下面的程序中B == AC == B是错误的.

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);
        }
    }
}

输出:

错误
错误

False
False

推荐答案

在.NET中,类是引用类型.引用类型有两件事. 对象 对象引用 .

In .NET, classes are reference types. Reference types has two thing. Object and a reference to object.

在您的情况下,A是对ObjectA的引用,B是对ObjectB的引用.

In your case, A is a reference to the ObjectA, B is a reference to the ObjectB.

定义Class1 C = A;

  • 首先,您创建两件事.名为 ObjectC 的对象和对名为 C 的对象的引用.
  • 然后将A的引用复制到C的引用.现在, A和C引用了同一对象.
  • 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.

对引用对象使用==时,如果引用的对象相同,则返回true,否则返回false.

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

在您的情况下,这就是B == AC == B返回false的原因,但是,如果尝试使用A == C,它将返回true.

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

这篇关于C#中的引用类型比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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