gpt4 book ai didi

c# - 空字符串作为特例?

转载 作者:IT王子 更新时间:2023-10-29 03:47:32 26 4
gpt4 key购买 nike

我读了 Jon Skeet 的测验,我想知道为什么我的第二个样本不起作用而第一个样本起作用。

为什么这会产生 true :

object x = new string("".ToArray());
object y = new string("".ToArray());
Console.WriteLine(x == y); //true

但这个不是:

var k="k";
//string.intern(k); // doesn't help
object x = new string(k.ToArray());
object y = new string(k.ToArray());
Console.WriteLine(x == y); //false

我在 vs2010 上使用 fw 4.5。

幸运的是我也安装了 vs2005,同样的结果:

enter image description here

最佳答案

这是 Eric Lippert 的一篇博文,它回答了您的问题:String interning and String.Empty .

他描述了类似的情况:

object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;
Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true
Console.WriteLine(obj == str2); // false !?

所以想法是,实习并不意味着您只有一个特定 string 的实例,即使它是实习的。 默认情况下仅驻留编译时文字。这意味着以下代码打印为真:

var k1 = "k";
object k2 = "k";
Console.WriteLine(k1 == k2);

但是,如果您尝试在运行时以编程方式创建包含 "k" 内容的字符串,例如使用 string(char[]) 构造函数,在对象上调用 ToString(),使用 StringBuilder 等,您不会得到 interned string默认。这个打印错误;

var k1 = "k";
object k2 = new string("k".ToCharArray());
Console.WriteLine(k1 == k2);

为什么?因为在运行时驻留字符串是昂贵的。

There Ain't No Such Thing As A Free Lunch.

(...)

In short, it is in the general case not worth it to intern all strings.

关于空字符串的不同行为:

Some versions of the .NET runtime automatically intern the empty string at runtime, some do not!

关于c# - 空字符串作为特例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22138144/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com