两种不同的"串"是同一个对象实例? [英] Two different "strings" are the same object instance?

查看:124
本文介绍了两种不同的"串"是同一个对象实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code是pretty言自明。我希望当我做出 A1 B1 ,我是创建包含相同的文本两个不同的字符串实例。所以我想 A1 == B1 将是真实的,但<​​code> object.ReferenceEquals(A1,B1)是假的,但事实并非如此。为什么呢?

  //使两个看似不同的字符串实例
字符串A1 =测试;
串B1 =测试;
Console.WriteLine(object.ReferenceEquals(A1,B1)); //打印true。为什么?//明确将再造B2
字符串A2 =测试;
串B2 =TES
B2 + =T;
Console.WriteLine(object.ReferenceEquals(A2,B2)); //打印假//明确使用新的字符串构造
字符串A3 =新的字符串(测试.ToCharArray());
串B3 =新的字符串(测试.ToCharArray());
Console.WriteLine(object.ReferenceEquals(A3,B3)); //打印假


解决方案

文字字符串对象都合并为编译器的单实例。这实际上是通过规范需要


  

每个字符串不一定产生新的字符串实例。当两个或多个字符串,根据字符串相等运算符(第7.9.7)是等效的出现在同一个组件,这些字符串引用相同的字符串实例。


The code is pretty self explanatory. I expected when I made a1 and b1 that I was creating two different string instances that contain the same text. So I figure a1 == b1 would be true but object.ReferenceEquals(a1,b1) would be false, but it isn't. Why?

//make two seemingly different string instances
string a1 = "test";
string b1 = "test";         
Console.WriteLine(object.ReferenceEquals(a1, b1)); // prints True. why?

//explicitly "recreating" b2
string a2 = "test";
string b2 = "tes";
b2 += "t";    
Console.WriteLine(object.ReferenceEquals(a2, b2)); // prints False

//explicitly using new string constructor
string a3 = new string("test".ToCharArray());
string b3 = new string("test".ToCharArray());    
Console.WriteLine(object.ReferenceEquals(a3, b3)); // prints False

解决方案

Literal string objects are coalesced into single instances by the compiler. This is actually required by the specification:

Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance.

这篇关于两种不同的&QUOT;串&QUOT;是同一个对象实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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