2014-01-15 29 views
1

,這個問題就我這個共同的代碼示例frecuently用來解釋值類型和引用類型之間的區別:C#如何獲取引用類型的行爲與字符串?

class Rectangle 
{ 
    public double Length { get; set; } 
} 

struct Point 
{ 
    public double X, Y; 
} 

Point p1 = new Point(); 
p1.X = 10; 
p1.Y = 20; 
Point p2 = p1; 
p2.X = 100; 
Console.WriteLine("p1.X = {0}", p1.X); 

Rectangle rect1 = new Rectangle 
{ Length = 10.0, Width = 20.0 }; 
Rectangle rect2 = rect1; 
rect2.Length = 100.0; 
Console.WriteLine("rect1.Length = {0}",rect1.Length); 

在這種情況下,第二個Console.WriteLine語句將輸出:「rect1.Length = 100 「

在這種情況下,類是引用類型,struct是值類型。我如何使用字符串來展示相同的引用類型行爲?

在此先感謝。

+5

你不能。字符串是不可變的。 –

回答

5

你不能。字符串是不可變的,這意味着你不能直接改變它們。對字符串的任何更改實際上都是返回的新字符串。

因此,這(我假定你的意思):

string one = "Hello"; 
string two = one; 

two = "World"; 

Console.WriteLine(one); 

..will打印 「Hello」,因爲two現在是一個全新的字符串和one保持原樣。做一個字符串

+0

那麼爲什麼他們使用該代碼示例來解釋引用類型行爲? int和string之間有什麼區別? –

+0

字符串是引用類型..但它們似乎具有值類型語義,因爲它們是不可變的。 「int'和'string'之間的區別」..?在什麼情況下? (事實上​​他們是完全不同的東西) –

+0

你是對的西蒙。謝謝。標記爲答案。 –

1

唯一的辦法一提的是,以使用StringBuilder

class Program 
{ 
    static void Main(string[] args) 
    { 

     string one = "Hello"; 
     string two = one; 

     two = "World"; 

     Console.WriteLine(one); 

     StringBuilder sbone = new StringBuilder("Hello"); 
     StringBuilder sbtwo = sbone; 

     sbtwo.Clear().Append("world"); 

     Console.WriteLine(sbone); 


     Console.ReadKey(); 
    } 
} 
1

怎麼樣建立一個10MB的長字符串,然後設置一個非常大的陣列中的所有元素等於它,使用任務管理器您可能能夠顯示內存使用率沒有增加。

請注意創建數組之後但在將字符串設置爲數組元素之前的進程大小。

1

字符串的引用類型。它是一個不可變的(只讀)引用類型。因爲它是不可變的,所以每次使用運算符(例如++=等)修改它時都會創建一個新實例。

字符串是隻讀的這一事實使得它們的行爲類似於值類型。

1

像這樣(不這樣做,雖然):

string a = "Hello"; 
string b = a; 

unsafe 
{ 
    fixed(char* r = a) 
    { 
     r[0] = 'a'; 
    } 
    Console.WriteLine(a); 
    Console.WriteLine(b); 
} 
相關問題