C# pass by value/ref?

前端 未结 4 1700
借酒劲吻你
借酒劲吻你 2020-12-05 04:58

Common question but I could use an \"english\" explanation.

Is it like Java where

Cat myCat

actually is a pointer to Cat

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 05:42

    As @rstevens answered, if it is a class, myCat is a reference. But if you pass myCat to a method call, then the reference itself is passed by value - i.e. the parameter itself will reference the same object, but it's a completely new reference, so if you assign it to null, or create a new object, the old myCat reference will still point to the original object.

    SomeMethod(myCat);
    
    void SomeMethod(Cat cat)
    {
        cat.Miau(); //will make the original myCat object to miau
        cat = null; //only cat is set to null, myCat still points to the original object
    }
    

    Jon Skeet has a good article about it.

提交回复
热议问题