[英]new String() doesn't create new reference object in c#?
Edit: 编辑:
Why this question is not duplicate? 为什么这个问题不是重复的? I'm not asking difference between
.Equals()
and ==
. 我不是问
.Equals()
和==
之间的.Equals()
。 I'm asking how does actually ==
work. 我问实际上
==
如何工作。 I mean, when I created strings using different method, I should have seen different result. 我的意思是,当我使用不同的方法创建字符串时,我应该看到不同的结果。 But I see same result.
但我看到相同的结果。
I was looking into ==
operator in c#. 我正在研究C#中的
==
运算符。 To my surprise it gave same result for following codes (contrary to JAVA). 令我惊讶的是,它对以下代码给出了相同的结果(与JAVA相反)。 But according to this ,
==
is for reference check and I should see different result for my code then why do I see same result for both of them? 但根据这个 ,
==
参考检查,我应该看到不同的结果,我的代码,那么为什么我看到他们两个相同的结果? Shouldn't I see different results for my piece of codes? 我的代码片段应该不会看到不同的结果吗? Is it because
new String()
in c# doesn't generate new reference? 是否因为c#中的
new String()
不会生成新引用?
String s = "abc";
String s1 = "abc";
Console.WriteLine("Expected output: True, Actual output: " + (s1==s).ToString());
Output 输出量
Expected output: True , Actual output: True
预期输出: True ,实际输出: True
Another code check 另一个代码检查
String s2 = new String("abc".ToCharArray());
String s3 = new String("abc".ToCharArray());
Console.WriteLine("Expected output: False, Actual output: " + (s2 == s3).ToString());
Output 输出量
Expected output: False , Actual output: True
预期输出: False ,实际输出: True
Note: I understand difference reference & value check. 注意:我了解差异参考和价值检查。 I've tried result with
ReferenceEquals
and it shows expected result to me. 我已经使用
ReferenceEquals
尝试了结果,它向我显示了预期的结果。
Normally for reference types ==
operator do check for reference equality. 通常对于引用类型
==
运算符,请检查引用是否相等。
String is also a reference type but in String class ==
operator is overloaded to check for content equality and not reference equality. 字符串也是引用类型,但在字符串类中,
==
运算符被重载以检查内容是否相等而不是引用是否相等。
It says and I quote 它说,我引用
Determines whether two specified strings have the same value.
Read here https://msdn.microsoft.com/en-us/library/system.string.op_equality(v=vs.110).aspx 在这里阅读https://msdn.microsoft.com/zh-cn/library/system.string.op_equality(v=vs.110).aspx
FYI, in string !=
operator is also oveloaded to check for string content inequality. 仅供参考,在字符串
!=
运算符中也可以检查字符串内容是否不相等。
在c#中,运算符==
用于字符串比较值,而不是引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.