更新:2007 年 11 月
本示例演示在向方法传递
本示例的输出表明:当向 ClassTaker 方法传递类实例时,只更改类字段的值。但是向 StructTaker 方法传递结构实例并不更改结构字段。这是因为向 StructTaker 方法传递的是结构的副本,而向 ClassTaker 方法传递的是对类的引用。
示例
C# | 复制代码 |
---|---|
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 */ |