C# pass by value/ref?

前端 未结 4 1705
借酒劲吻你
借酒劲吻你 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条回答
  •  旧时难觅i
    2020-12-05 05:44

    Yes, it's about pointers but not really... The thing that messed me up originally is that it isn't really about about protecting your variable from changes within the method. If you change the object within the method, those changes are visible to the external methods regardless of whether it is passed in "ref" or not.

    The difference (as I understand it) is whether the variable you send in has its reference updated coming back out if you change the object that variable references. So given this method

    public void DoSomething(ref CoolShades glasses)
    {
        glasses.Vendor = "Ray Ban";
        glasses = new CoolShades();
    }
    

    the variable you passed in as a parameter now contains a reference to the new CoolShades rather than whatever object it referenced before. The original parameter object's Vendor property will be changed to "Ray Ban" regardless of whether you passed the parameter ref or not.

提交回复
热议问题