问题描述
为什么在这种情况下的ReferenceEquals
对象的方法具有不同的行为?
Why in this situation ReferenceEquals
method of object behaves differently?
string a= "fg";
string b= "fg";
Console.WriteLine(object.ReferenceEquals(a, b));
因此,在这种情况下,它得到的结果真正
。在情况下,比较了我的琴弦,而不是参考值。但是,当我写的东西,如:
So in this situation it's get a result true
. In case, it compares values of my strings and not references. But when I write something like:
StringBuilder c = new StringBuilder("fg");
string d = c.ToString();
Console.WriteLine(object.ReferenceEquals(a, d));
在此情况下,它工作正常,结果是假
,因为它比较我的对象的引用。
In this case it works fine and result is false
, because it compares references of my objects.
推荐答案
第一个例子有一个编译时间常数由两个变量引用FG
。由于这是一个编译时间常数,所述两个变量引用一个对象。该引用是等价的。
The first example has a compile time constant "fg"
that is referenced by two variables. Since this is a compile time constant, the two variables reference the one object. The references are equal.
读入的的字符串实习的更多关于这种行为的话题。作为首发,考虑:
Read into the topic of string interning for more on this behavior. As a starter, consider:
例如,如果您在同一文本字符串分配给几个变量,运行时获取相同的参考从实习生池的文字字符串,并将其分配给每个变量。
的
在第二个例子中,只有一个是一个编译时间常数,另一种是某些操作的结果。 A
和 D
不引用相同的对象,所以你从错误结果的ReferenceEquals
。
In the second example, only one is a compile time constant, the other is a result of some operations. a
and d
do not reference the same object, so you get the false result from ReferenceEquals
.
这篇关于使用的ReferenceEquals字符串错误工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!