C#中的Reference类型和ref有什么区别?

What is the difference between Reference type and ref in C#?

本问题已经有最佳答案,请猛点这里访问。

ref类型和Reference type类型中,我都可以改变对象的值,那么它们之间的区别是什么?

有人给了我答案,但我还是不清楚。

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;
    }
}


一个ref关键字参数提供参考参考的对象,在那里你可以改变在这个参考点后,要更改

1
2
3
4
5
6
7
8
9
public void TestObject(Person person)
{
    person = new Person { Name ="Two" };
}

public void TestObjectByRef(ref Person person)
{
    person = new Person { Name ="Two" };
}

然后,当你使用这些方法

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.

当你传递一个引用类型参数的方法没有ref关键字参考指南作为复制对象传递。你可以改变值(属性)的对象,但如果你设置它的引用另一个对象,它不会影响原来的参考。