Reference to reference in C#?

前端 未结 6 1583
花落未央
花落未央 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:52

    This is best illustrated with an example:

    public class C { public int P { get; set; } }
    public class X
    {
        static void M(C c1, C c2, ref C c3, ref C c4)
        {
          c1.P = 11;
          c2 = new C() { P = 12 };
          c3.P = 13;
          c4 = new C() { P = 14 };
        }
        static void Main()
        {
          C q1 = new C() { P = 1 };
          C q2 = new C() { P = 2 };
          C q3 = new C() { P = 3 };
          C q4 = new C() { P = 4 };
          M(q1, q2, ref q3, ref q4);
          Console.WriteLine(q1.P);
          Console.WriteLine(q2.P);
          Console.WriteLine(q3.P);
          Console.WriteLine(q4.P);
        }
    }
    

    What happens?

    q1 and c1 refer to the same object but are different variables. Mutating c1.P mutates q1.P because both variables refer to the same object, so q1 is now 11.

    q2 and c2 refer to the same object but are different variables. Mutating c2 does not mutate q2 because c2 and q2 are different variables; changing one does not change the other. q2 stays 2, and the new object is lost.

    q3 and c3 are two names for the same variable, and therefore refer to the same object. When you change c3.P that changes q3.P automatically because they are two names for the same thing.

    q4 and c4 are two names for the same variable, and therefore mutating q4 also mutates c4.

    Does that make sense?

    It is unfortunate that the keyword for "make an alias to this variable" is "ref". It would have been more clear had it been "alias".

    To answer your second question: no, this does not make a chain of references. Let's make a more clear example:

    ...
    int c1 = 123;
    M(ref c1);
    ...
    void M1(ref int q1) { M2(ref q1); }
    void M2(ref int q2) { M2(ref q2); }
    

    This says that c1 and q1 are different names for the same variable, and q1 and q2 are different names for the same variable, and therefore c1, q1 and q2 are all aliases for each other. There's never a "reference to reference to variable" in C# the way there is in C++.

提交回复
热议问题