为什么在以下情况下我们有不同的输出:
object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;
Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true
Console.WriteLine(obj == str2); // false !?
答案很简单:
当您将和object
与进行string
比较时,将使用引用比较,只有两个对象具有相同的引用时,该比较才为true。
比较字符串时,将使用字符串比较,如果字符串内容相同,则无论它们是否是相同的引用,该比较都是正确的。
在第三个比较中,您使用的object
是比较两个内容相同但引用不同的字符串,因此它将返回false。
更为复杂的是,前两个字符串具有相同的引用,因为它们是编译时常量,并且已由interned
编译器使用,因此它们引用内存中的同一字符串。
我用以下解释注释了您的原始代码:
object obj = "Int32"; // As a compile-time constant string, this will be interned.
string str1 = "Int32"; // This is also interned, so has the same reference as obj
string str2 = typeof(int).Name; // Same contents as str1, but a different reference
// (created at runtime, so it wasn't interned)
Console.WriteLine(obj == str1); // Reference comparison: true because the references are the same
Console.WriteLine(str1 == str2); // String comparison: true because the string contents are the same.
Console.WriteLine(obj == str2); // Reference comparison: false because the references different.
还:
您可以通过声明str2来获得相同的结果,如下所示:
字符串str2 = string.Concat(“ Int”,“ 32”);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句