为什么的ReferenceEquals(S1,S2)返回true [英] why does ReferenceEquals(s1,s2) returns true
问题描述
String s1 = "Hello";
String s2 = "Hello";
下面S1,S2是不同的,但为什么的ReferenceEquals()的返回true
Here s1, s2 are different but then why ReferenceEquals() is returning true
推荐答案
这是由于的实习的 - CLI中自动重新使用一个字符串获得的为文字(即那些直接从源代码来串)。请注意,如果你这样做:
This is due to interning - the CLI automatically re-uses strings obtained as literals (i.e. strings that have come directly from your source code). Note that if you did:
char[] chars = {'h','e','l','l','o'};
string s1 = new string(chars);
string s2 = new string(chars);
他们的不可以是相同的字符串实例,因为他们还没有来从文字。
they would not be the same string instance, as they have not come from literals.
这是记载针对的 Ldstr
IL指令:
This is documented against the Ldstr
IL instruction:
通用语言基础结构(CLI)保证两个ldstr指令指的是具有相同的字符序列的两个元数据标记返回结果完全相同的字符串对象(被称为串实习的过程)。
The Common Language Infrastructure (CLI) guarantees that the result of two ldstr instructions referring to two metadata tokens that have the same sequence of characters return precisely the same string object (a process known as "string interning").
这篇关于为什么的ReferenceEquals(S1,S2)返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!