先贴代码
namespace ConsoleApplication6 { class Program { static void Main(string[] args) { Test1(); Test2(); Test3(); } private static void Test1() { var a = new DataModel() { Value = 1 }; var b = a; a = new DataModel() { Value = 2 }; Console.WriteLine($"a = {a.Value}"); Console.WriteLine($"b = {b.Value}"); //Output: a=2 b=1 } private static void Test2() { var a = new DataModel() { Value = 1 }; ChangeVal(a); Console.WriteLine($"a = {a.Value}"); //Output: a=1 b=1 c=2 } private static void Test3() { var a = new DataModel() { Value = 1 }; ChangeVal(ref a); Console.WriteLine($"a = {a.Value}"); //Output: a=2 b=1 c=2 } private static void ChangeVal(DataModel c) { var b = c; c = new DataModel() { Value = 2 }; Console.WriteLine($"b = {b.Value}"); Console.WriteLine($"c = {c.Value}"); } private static void ChangeVal(ref DataModel c) { var b = c; c = new DataModel() { Value = 2 }; Console.WriteLine($"b = {b.Value}"); Console.WriteLine($"c = {c.Value}"); } } public class DataModel { public int Value { get; set; } } }
Test1() b=a之后b指向了同一块内存地址,a重新赋值后a指向了另一块内存地址
Test2() 函数传递参数,实际地址发生了改变,参数重新实例化后,指向了另一个内存地址
Test3() 使用ref关键字后传递了一样的地址,所以后面修改c的值就是修改a的值