What is the difference between Reference type and ref in C#?
本问题已经有最佳答案,请猛点这里访问。
在
有人给了我答案,但我还是不清楚。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | static void Main(string[] args) { myclass o1 = new myclass(4,5); Console.WriteLine("value of i={0} and j={1}", o1.i, o1.j); //o/p=4,5 o1.exaple(ref o1.i, ref o1.j); //Ref type calling Console.WriteLine("value of i={0} and j={1}", o1.i, o1.j);// o/p=2,3 myclass o2 = o1; Console.WriteLine("value of i={0} and j={1}", o2.i, o2.j); // o/p 2,3 o1.i = 100; o1.j = 200; Console.WriteLine("value of i={0} and j={1}", o1.i, o1.j); //o/p=100,200 Console.WriteLine("value of i={0} and j={1}", o2.i, o2.j); //o/p=100,200 Console.ReadKey(); } public class myclass { public int i; public int j; public myclass(int x,int y) { i = x; j = y; } public void exaple(ref int a,ref int b) //ref type { a = 2; b = 3; } } |
一个
1 2 3 4 5 6 7 8 9 |
然后,当你使用这些方法
1 2 3 4 5 6 7 | var person = new Person { name ="One" }; TestObject(person); Console.WriteLine(person.Name); // will print One TestObjectByRef(ref person); Console.WriteLine(person.Name); // will print Two |
下面一排从MSDN:http://。/en-US /图书馆/ 14akc2c7.aspx
The ref keyword causes an argument to be passed by reference, not by
value. The effect of passing by reference is that any change to the
parameter in the called method is reflected in the calling method. For
example, if the caller passes a local variable expression or an array
element access expression, and the called method replaces the object
to which the ref parameter refers, then the caller’s local variable or
the array element now refer to the new object.
当你传递一个引用类型参数的方法没有