Reference to reference in C#?

前端 未结 6 1586
花落未央
花落未央 2021-02-05 18:24

As we all know, C# classes object are treated as references, so what happens when you pass a reference object as a reference to a method? Say we have:

public cla         


        
6条回答
  •  执笔经年
    2021-02-05 18:56

    When you pass a object as parameter of a method, you pass a new pointer that references to the original object. If you pass a object as ref parameter, you pass the same pointer that uses the caller method. An example,

    public void F(ref A a, A b){
        a = new A(1);
        b.Property = 12;
        b = new B(2);
    }
    
    public void G(){
        A a = new A(0);
        A b = new A(0);
        F(a,b);
        System.Console.WriteLine(a + " - " + b);
    }
    

    The output is 1 - 12 because the pointer of object b doesn't change but the original object changes.

提交回复
热议问题