在 ref
类型和 Reference 类型
中,我都可以更改对象的值,那么它们之间有什么区别?
有人提供了 answer但我还是不清楚。
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;
}
}
带有 ref
关键字的参数提供对对象引用的引用,您可以在其中更改此引用在更改后指向的位置
public void TestObject(Person person)
{
person = new Person { Name = "Two" };
}
public void TestObjectByRef(ref Person person)
{
person = new Person { Name = "Two" };
}
然后当你使用那些方法的时候
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 的引述:https://msdn.microsoft.com/en-us/library/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.
当您将引用类型作为参数传递给没有 ref
关键字的方法时,对作为副本传递的对象的引用。您可以更改对象的值(属性),但如果将其设置为引用另一个对象,则不会影响原始引用。