HOW TO:了解傳遞結構和傳遞類別參考給方法之間的差異 (C# 程式設計手冊)
本範例介紹當傳遞結構至方法上時,所傳遞的是結構的複本,但是當傳遞類別執行個體時,傳遞的則是參考。
下列程式碼的輸出顯示,當類別執行個體傳遞到 ClassTaker 方法時,類別欄位的值會變更。 但是,結構欄位並會不隨著其執行個體傳遞到 StructTaker 方法而變更。 這是因為傳遞到 StructTaker 方法的是結構的複本,而傳遞到 ClassTaker 方法的是類別的參考。
範例
class TheClass
{
public string willIChange;
}
struct TheStruct
{
public string willIChange;
}
class TestClassAndStruct
{
static void ClassTaker(TheClass c)
{
c.willIChange = "Changed";
}
static void StructTaker(TheStruct s)
{
s.willIChange = "Changed";
}
static void Main()
{
TheClass testClass = new TheClass();
TheStruct testStruct = new TheStruct();
testClass.willIChange = "Not Changed";
testStruct.willIChange = "Not Changed";
ClassTaker(testClass);
StructTaker(testStruct);
Console.WriteLine("Class field = {0}", testClass.willIChange);
Console.WriteLine("Struct field = {0}", testStruct.willIChange);
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
Class field = Changed
Struct field = Not Changed
*/