Reference to reference in C#?

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

    Simply stated, passing a variable as a ref parameter is like creating an alias for the original variable.

    Reference types and reference parameters are distinct entities. In C # variables are always pass by value. That value may be a reference to another object or a stored value.

    In other words, reference types are "passed by reference" because when you pass an object instance to a method the method gets a reference to the object instance.
    In the case of reference parameters the reference is to the variable (hence why it makes sense to think of this an an alias). This is a different form of "passing by reference".

    Going by your example:

    public void F(ref A a)
    {
        F(ref a);
    }
    

    Here its like we have a single object (the original parameter a) that is referenced infinite times. (Note that this isn't what actually happens). This diagram is intended to provide an idiomatic representation of what happens under the covers when dealing with reference parameters.

    enter image description here

    See section 1.6.6.1 of the 4.0 C# spec for more info.

提交回复
热议问题