昨日、ここに質問への回答を投稿していたとき、どのように問題が発生しString.Equals
、==
状況によって動作が異なりました。
結論String.Equals
と==
行動が欲しい。
bool result = false;
object obj = "String";
string str2 = "String";
string str3 = typeof(string).Name;
string str4 = "String";
object obj2 = str3;
// obj, str2, str4 references are same.
// obj is object type and others are string type
// Comparision between object obj and string str2 -- Com 1
result = String.Equals(obj, str2);// true
result = String.ReferenceEquals(obj, str2); // true
result = (obj == str2);// true
// Comparision between object obj and string str3 -- Com 2
result = String.Equals(obj, str3);// true
result = String.ReferenceEquals(obj, str3); // false
result = (obj == str3);// false
// Comparision between object obj and string str4 -- Com 3
result = String.Equals(obj, str4);// true
result = String.ReferenceEquals(obj, str4); // true
result = (obj == str4);// true
// Comparision between string str2 and string str3 -- Com 4
result = String.Equals(str2, str3);// true
result = String.ReferenceEquals(str2, str3); // false
result = (str2 == str3);// true
// Comparision between string str2 and string str4 -- Com 5
result = String.Equals(str2, str4);// true
result = String.ReferenceEquals(str2, str4); // true
result = (str2 == str4);// true
// Comparision between string str3 and string str4 -- Com 6
result = String.Equals(str3, str4);// true
result = String.ReferenceEquals(str3, str4); // false
result = (str3 == str4);// true
// Comparision between object obj and object obj2 -- Com 7
result = String.Equals(obj, obj2);// true
result = String.ReferenceEquals(obj, obj2); // false
result = (obj == obj2);// false
時計も見る
obj "String" {1#} object {string}
str2 "String" {1#} string
str3 "String" {6#} string
str4 "String" {1#} string
obj2 "String" {6#} object {string}
Com1、Com2、Com3、Com4、Com5、および Com6 の動作が異なるのはなぜですか?