奇怪的字符串对比 [英] Strange string literal comparison

查看:214
本文介绍了奇怪的字符串对比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中不断深入,我也遇到了对象引用相等有点(奇怪)的问题。
让说,我有两个字符串:

Going deeper in C#, I have encountered a little (strange) problem with object reference equality. Let says I have two strings:

String a = "Hello world!";
String b = "Bonjour le monde";
bool equals = ReferenceEquals(a, b);  // ******************* (1)
b = "Hello world!";
equals = ReferenceEquals(a, b);       // ******************* (2)

(1)和预期。
的ReferenceEquals 文档说:

的ReferenceEquals比较实例

ReferenceEquals compares instances

但随后:


  • 为什么(2)返回真正

  • 字符串 A b 是不一样的对象是什么人?如果是的话那么他们怎么成为同一给定,我从来没有明确 A = B

  • Why does (2) returns true?
  • Strings a and b are not the same object are they? If yes then how did they become the same given that I never explicitly did a=b

推荐答案

这是因为的字符串实习

公共语言运行库通过维护
表节省字符串存储,所谓实习生池,包含一个参考
声明或$ b $程序创建的b您的程序每一个独特的文本字符串。因此,文字串用
特定值的实例只存在于系统中一次。

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

例如,如果您在同一文本字符串分配给多个
变量,运行时获取相同的参考,从实习生池字面
字符串,并将其分配给每个变量。

For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.

这篇关于奇怪的字符串对比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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