2010-08-11 96 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。它告訴你所有你需要知道的。

相關問題