MSDN称:
String.Intern检索系统对指定字符串的引用。
和
String.IsInterned检索指定字符串的引用。
我认为IsInterned应该返回一个bool值,表示指定的字符串是否被内部化了。这个想法正确吗?我是说,它至少不符合.net框架的命名约定。
我编写了以下代码:
string s = "PK";
string k = "PK";
Console.WriteLine("s has hashcode " + s.GetHashCode());
Console.WriteLine("k has hashcode " + k.GetHashCode());
Console.WriteLine("PK Interned " + string.Intern("PK"));
Console.WriteLine("PK IsInterned " + string.IsInterned("PK"));
输出结果如下:
输出为:
s 的哈希码为 -837830672
k 的哈希码为 -837830672
PK Interned PK
PK IsInterned PK
为什么 string.IsInterned("PK") 返回 "PK"?
GetHashCode()
方法的备注:请注意,System.String
类覆盖了GetHashCode()
方法。因此,这样的方法调用不能用于检查实例是否可能不同。相反,包括一个using System.Runtime.CompilerServices;
指令并使用RuntimeHelpers.GetHashCode(string)
方法。以下是一个很好的例子:string s = "PK"; string t = 'P'.ToString() + "K"; Console.WriteLine("s has non-overridden hashcode " + RuntimeHelpers.GetHashCode(s)); Console.WriteLine("t has non-overridden hashcode " + RuntimeHelpers.GetHashCode(t));
。 - Jeppe Stig Nielsen