他们真的一样吗?今天,我遇到了这个问题.这是立即窗口的转储:
?s
"Category"
?tvi.Header
"Category"
?s == tvi.Header
false
?s.Equals(tvi.Header)
true
?s == tvi.Header.ToString()
true
Run Code Online (Sandbox Code Playgroud)
所以,无论是s和tvi.Header包含"类别",而是==返回false,并Equals()返回true.
s被定义为字符串,tvi.Header实际上是一个WPF TreeViewItem.Header.那么,他们为什么会回归不同的结果呢?我一直认为它们可以在C#中互换.
任何人都可以解释为什么会这样吗?
我想知道特定于.Net框架的字符串实习的过程和内部.还想知道使用实习的好处以及我们应该使用字符串实习来提高性能的场景/情况.虽然我已经从Jeffery Richter的CLR书中学习实习,但我仍然感到困惑,并希望更详细地了解它.
[编辑]使用示例代码询问具体问题如下:
private void MethodA()
{
string s = "String"; // line 1 - interned literal as explained in the answer
//s.intern(); // line 2 - what would happen in line 3 if we uncomment this line, will it make any difference?
}
private bool MethodB(string compareThis)
{
if (compareThis == "String") // line 3 - will this line use interning (with and without uncommenting line 2 above)?
{
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)