.NET 编译器如何比较两个字符串?
string a="I am comparing 2 string";
string b="I am comparing 2 string";
if(a==b)
return true;
else
return false;
.NET 编译器如何比较两个字符串?字符串的工作方式与 struct(int) 类似吗? string 是类,所以 a=b 意味着我们正在比较 2 个对象,但我想比较 2 个值。
string a="I am comparing 2 string";
string b="I am comparing 2 string";
if(a==b)
return true;
else
return false;
How does a .NET compiler compare two strings? Does a string work like a struct(int)?
string is class so a=b means we are comparing 2 object, but i want to compare 2 values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
String 类重载了
==
运算符,因此它会比较字符串的值,就像比较int
等值类型一样。(顺便说一句,编译器还在代码中插入文字字符串,因此字符串变量
a
和b
实际上将引用同一个字符串对象。如果您使用 < code>Object.ReferenceEquals(a,b) 它也会返回true
。)The String class overloads the
==
operator, so yes it compares the values of the strings, just like comparing value types likeint
.(On a side note, the compiler also interns literal strings in the code, so the string variables
a
andb
will actually be referencing the same string object. If you useObject.ReferenceEquals(a,b)
it will also returntrue
.)System.String
是一个重载了==
运算符来比较字符串内容的类。这使得它在比较中是“类似值”,但在其他方面仍然是引用类型。System.String
is a class which has the==
operator overloaded to compare the content of the strings. This allows it to be "value like" in comparison and yet still be a reference type in other respects.C# 字符串
C# string
字符串是由运行时而不是编译器进行比较的。比较由 Equality 运算符执行。
Strings are compared by the Runtime, not the compiler. Comparison is performed by Equality operator.
这里有不同的事情需要记住。
首先,所有相同的常量字符串都将被保留,以便两个引用在开始时相等。因此,即使您在这里执行了
ReferenceEquals()
,您也会得到“true”结果。因此,只有对于构建的字符串(例如使用StringBuilder
或从文件中读取等),您才会获得另一个引用,因此在进行引用相等比较时为 false。如果在编译时已知两个对象都是字符串,则编译器将发出代码来比较它们的值(
==
System.String
上的重载运算符),而不是它们的引用。请注意,一旦将其与object
类型引用进行比较,情况就不再是这样了。不会执行运行时检查来按值比较字符串,并且编译器不会为
==
运算符发出.Equals()
调用。There are different things to keep in mind here.
First, all identical constant strings will be interned so that both references are equal to start with. Therefore, even if you did a
ReferenceEquals()
here, you'd get "true" as result. So only for a string built (for instance with aStringBuilder
, or read from a file etc.) you'd get another reference and therefore false when doing a reference equality comparison.If both objects are known to be strings at compile time, the compiler will emit code to compare their value (
==
overloaded operator onSystem.String
), not their references. Note that as soon as you compare it against anobject
type reference, this isn't the case anymore.No runtime check is done to compare a string by value, and the compiler does not emit a
.Equals()
call for the==
operator.请注意,您的问题有点棘手。因为 ReferenceEquals 也会返回 true。
这是因为实习:http://en.wikipedia.org/wiki/String_interning
Notice that your question is a little tricky. Because ReferenceEquals will ALSO return true.
This is because of Interning : http://en.wikipedia.org/wiki/String_interning