我在Silverlight应用程序中有一个比较2个字符串的条件,由于某种原因,当我使用==它时返回false而.Equals()返回true.
这是代码:
if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack"))
{
// Execute code
}
if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack")
{
// Execute code
}
Run Code Online (Sandbox Code Playgroud)
任何理由为什么会这样?
我想知道特定于.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) 我在运行程序时使用 Visual Studio 的监视面板来调查变量。在以下代码中,test1和test2变量都添加到“监视”面板中。正如预期的那样,它们的评估结果都是true。
object a = "123";
object b = "123";
bool test1 = a == b;
bool test2 = (object)"123" == (object)"123";
Run Code Online (Sandbox Code Playgroud)
但是,如第三行所示,如果我手动添加test2变量的表达式,则其计算结果为false。
为什么同一行在 Watch 窗口中产生不同的结果?这是这里工作的某种优化吗?什么情况下可以将同一个字符串分配到不同的地址?
var str1 = "C#";\nvar str2 = "F#"; \nvar str3 = "C#";\n\nConsole.WriteLine(Object.ReferenceEquals(str1, str2)); // False\nConsole.WriteLine(Object.ReferenceEquals(str1, str3)); // True <-- Why?\nRun Code Online (Sandbox Code Playgroud)\n我知道字符串是不可变的引用类型,这意味着对象不能更改。但这并不能解释为什么两个字符串引用同一个对象。
\n