代码阻止
string c = "Hello", d = "Hello";
Console.WriteLine("c is of Type : {0}, d is of Type : {1} ", c.GetType(),d.GetType());
Console.WriteLine("c==d {0}", object.ReferenceEquals(c, d));
Console.WriteLine("c and d hashCode are equal {0}",
c.GetHashCode() == d.GetHashCode());
输出
c的类型为:System.String,d的类型为:System.String
c == d True
c和d hashCode等于True
代码阻止
string e = "Hello", f = "Hello";
e += " world";
f += " world";
Console.WriteLine("e is of Type : {0}, f is of Type : {1} ", c.GetType(),d.GetType());
Console.WriteLine("e==f {0}", object.ReferenceEquals(e, f));
Console.WriteLine("e and d hashCode are equal {0}", e.GetHashCode() == f.GetHashCode());
输出
e的类型为:System.String,f的类型为:System.String
e == f False
e和f hashCode等于True
问题
Two different “strings” are the same object instance?
提到编译器已经过优化,它会自动引用相同的string
,这与变量c
和d
相关。
但是对于变量e
和f
,它应该指向相同的string
,因为e
和f
会重新分配给新+=
我们尝试对string
进行stings
操作时的参考(f
是不可变的),
但是根据上面的答案链接,变量e
应该已经分配给/opt/gitlab/embedded/service/gitlab-shell/hooks/
的引用,但根据输出,这两个变量被赋予了新的引用。为什么这样?