[英]What is the difference between String.Intern and String.IsInterned?
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"));
输出是:
s有哈希码-837830672
k有哈希码-837830672
PK Interned PK
PK IsInterned PK
为什么string.IsInterned(“PK”)返回“PK”?
如果字符串尚未实现,则String.Intern
该字符串; String.IsInterned
没有。
IsInterned("PK")
正在返回“PK”,因为它已经被实习。 它返回字符串而不是bool
是你可以很容易地获得对interned字符串本身的引用(它可能与你传入的引用不同)。 换句话说,它可以同时有效地返回两个相关的信息 - 您可以模拟它轻松返回bool
:
public static bool IsInternedBool(string text)
{
return string.IsInterned(text) != null;
}
我同意这个命名并不理想,虽然我不确定什么会更好:也许是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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.