C#中的引用类型比较 [英] Reference Type comparison in C#
问题描述
我正在尝试了解以下问题.我想知道为什么在下面的程序中B == A
和C == 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 ofC
. 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 == A
和C == 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屋!