2010-08-11 52 views
2

string是引用类型还是值类型?任何人都可以给出相应的描述?是字符串值类型还是引用类型

+2

闭幕票为“主观和议论”?关于这个问题,主观是什么? – Rob 2010-08-11 15:28:49

+0

对于这个问题,这个“不是一个真正的问题”? – 2010-08-11 17:45:42

回答

8

string是不可变引用类型。下面是一个简单的例子:

// All of these point to the same string in the heap 
string hello = "Hello World!"; // creates string 
string hello2 = "Hello World!"; // uses the previous string from the intern pool 
string hello3 = hello2; 

如果您正在寻找更多的信息,请查看乔恩斯基特的帖子:

C# in Depth: Strings in C# and .NET

3

在.NET Framework System.String是引用类型,一个很很好的解释是通过Jon Skeet:C# in Depth: Strings in C# and .NET。从他的文章的要点是:

  • 它是引用类型
  • 这是不可改变的
  • 它可以包含空值
  • 它重载==操作符

最后一点是使得string的行为有时像您可以编写的值类型:

string s1 = "value"; 
string s2 = "value"; 
// result will be true. 
bool result = (s1 == s2); 
+0

实际上这是一个不幸的例子 - 即使没有==重载,字串实习也会使其成为真实的。 – 2010-08-11 17:59:09

+0

@Jon - 我忘记了 - cantcha告诉它几乎是家乡时间! :S – Rob 2010-08-11 18:22:23

0

请查看我们自己的主人John Skeet从他的书“C#深度”中的章节Strings in C# and .NET。它告诉你所有你需要知道的。

相关问题