MSDN声明
String.Intern检索系统对指定String的引用
和
String.IsInterned检索对指定String的引用.
我认为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"));
Run Code Online (Sandbox Code Playgroud)
输出是:
s有哈希码-837830672
k有哈希码-837830672
PK Interned PK
PK IsInterned PK
为什么string.IsInterned("PK")返回"PK"?
Jon*_*eet 19
String.Intern如果字符串尚未被实习,则实习; String.IsInterned没有.
IsInterned("PK")正在回归"PK",因为它已经被实习了.它返回字符串而不是a的原因bool是,您可以轻松获取对实习字符串本身的引用(可能与您传入的引用不同).换句话说,它可以同时有效地返回两条相关的信息 - 您可以bool轻松地模拟它返回:
public static bool IsInternedBool(string text)
{
return string.IsInterned(text) != null;
}
Run Code Online (Sandbox Code Playgroud)
我同意这个命名并不理想,虽然我不确定会有什么更好:GetInterned也许吧?
这是一个显示差异的例子 - 我没有使用字符串文字,以避免事先被实习:
using System;
class Test
{
static void Main()
{
string first = new string(new[] {'x'});
string second = new string(new[] {'y'});
string.Intern(first); // Interns it
Console.WriteLine(string.IsInterned(first) != null); // Check
string.IsInterned(second); // Doesn't intern it
Console.WriteLine(string.IsInterned(second) != null); // Check
}
}
Run Code Online (Sandbox Code Playgroud)