c# - 字符串比较 == 是否仅因为字符串不可变才起作用?

标签 c# .net string

我之前在比较两个字符串和它们的变量时有一个想法:

string str1 = "foofoo";
string strFoo = "foo";
string str2 = strFoo + strFoo;

// Even thought str1 and str2 reference 2 different
//objects the following assertion is true.

Debug.Assert(str1 == str2);

这是否纯粹是因为 .NET 运行时识别字符串的值是相同的并且因为字符串是不可变的使得 str2 的引用等于 str1 的引用?

所以当我们执行 str1 == str2 时,我们实际上比较引用而不是不是值?我原本以为这是语法糖的产物,但我错了吗?

我写的有什么不准确的地方吗?

最佳答案

答案在 C# 规范 §7.10.7 中

The string equality operators compare string values rather than string references. When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different. As described in §7.10.6, the reference type equality operators can be used to compare string references instead of string values.

关于c# - 字符串比较 == 是否仅因为字符串不可变才起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8914095/

相关文章:

c# - 在 View 中显示从抽象基础派生的更多类型的最佳方式是什么?

c# - 如何从 LINQ to SQL 中的另一个项目获取连接字符串?

c# - .NET Compact Framework - 没有 ShowDialog 的模态表单

c# - 何时以及为何使用委托(delegate)?

javascript - 为什么当我输入 'names' 时,变量名称为 'name' 的数组会变成字符串?

string - 在 Fortran 中解析字符串

c# - 如何在 C# 中将列表值从一个类传递到其他形式?

.net - OleDb事务是否自动回滚?

string - 使用Delete()时发生访问冲突00000000;

C# "Semi-Generic"接口(interface)?