[英]What is the difference between String.Intern and String.IsInterned?
MSDN states that MSDN声明
String.Intern retrieves the system's reference to the specified String
String.Intern检索系统对指定String的引用
and 和
String.IsInterned retrieves a reference to a specified String.
String.IsInterned检索对指定String的引用。
I think that IsInterned should have returned (I know it doesn't) a bool stating whether the specified string is interned or not. 我认为IsInterned应该返回(我知道它没有)一个bool,说明指定的字符串是否被实习。 Is that correct thinking ?
这是正确的想法吗? I mean it is atleast not consistent with .net framework naming convention.
我的意思是它至少与.net框架命名约定不一致。
I wrote the following code: 我写了以下代码:
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"));
The output is : 输出是:
s has hashcode -837830672 s有哈希码-837830672
k has hashcode -837830672 k有哈希码-837830672
PK Interned PK PK Interned PK
PK IsInterned PK PK IsInterned PK
Why is string.IsInterned("PK") returning "PK"? 为什么string.IsInterned(“PK”)返回“PK”?
String.Intern
interns the string if it's not already interned; 如果字符串尚未实现,则
String.Intern
该字符串; String.IsInterned
doesn't. String.IsInterned
没有。
IsInterned("PK")
is returning "PK" because it's already interned. IsInterned("PK")
正在返回“PK”,因为它已经被实习。 The reason for it returning the string instead of a bool
is so that you can easily get a reference to the interned string itself (which may not be the same reference as you passed in). 它返回字符串而不是
bool
是你可以很容易地获得对interned字符串本身的引用(它可能与你传入的引用不同)。 In other words, it's effectively returning two related pieces of information at once - you can simulate it returning bool
easily: 换句话说,它可以同时有效地返回两个相关的信息 - 您可以模拟它轻松返回
bool
:
public static bool IsInternedBool(string text)
{
return string.IsInterned(text) != null;
}
I agree that the naming isn't ideal, although I'm not sure what would have been better: GetInterned
perhaps? 我同意这个命名并不理想,虽然我不确定什么会更好:也许是
GetInterned
?
Here's an example showing that difference though - I'm not using string literals, to avoid them being interned beforehand: 这是一个显示差异的例子 - 我没有使用字符串文字,以避免事先被实习:
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.