之前@BlueMonkMN提供的答案还有另一个方面需要考虑。这个方面是,回答@Drahcir标题问题的答案也取决于我们如何得到string
值。举个例子:
string s1 = "test";
string s2 = "test";
string s3 = "test1".Substring(0, 4);
object s4 = s3;
string s5 = "te" + "st";
object s6 = s5;
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2));
Console.WriteLine("\n Case1 - A method changes the value:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4));
Console.WriteLine("\n Case2 - Having only literals allows to arrive at a literal:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s5), s1 == s5, s1.Equals(s5));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s6), s1 == s6, s1.Equals(s6));
输出结果如下:
True True True
Case1 - A method changes the value:
False True True
False False True
Case2 - Having only literals allows to arrive at a literal:
True True True
True True True
==
运算符,但运算符不具有多态性。在这段代码中,==
运算符被调用到类型为object
的对象上,它进行的是身份比较而非值比较。 - Drew Noakes==
的左侧具有编译时类型为object
,右侧具有编译时类型为string
时,C#编译器必须选择(在这种情况下)存在问题的重载运算符operator ==(object, object)
;但它会发出编译时警告,指出可能是无意的。因此,请_阅读_编译时警告!要修复此问题并仍然使用==
,请将左侧转换为string
类型。如果我没记错,警告文本建议这样做。 - Jeppe Stig Nielsen