Why is the original object changed after a copy, without using ref arguments?

后端 未结 4 2057
渐次进展
渐次进展 2020-12-16 08:08

At work we were encountering a problem where the original object was changed after we send a copy through a method. We did find a workaround by using IClonable

4条回答
  •  甜味超标
    2020-12-16 08:41

    I see two issues here...

    Making a Copy of an object

    var copy = myClass; does not make a copy - what it really does is create a second reference ("pointer") to myClass (naming the variable "copy" is misleading). So you have myClass and copy pointing to the same exact object.

    To make a copy you have to do something like:

    var copy = new MyClass(myClass);
    

    Notice that I created a new object.

    Passing By Reference

    1. When passing value type variables without ref, the variable cannot be changed by the the receiving method.

      Example: DoSomething(int foo) - DoSomething cannot affect the value of foo outside of itself.

    2. When passing value type variables with ref, the variable can be changed

      Example: DoSomething(ref int foo) - if DoSomething changes foo, it will remain changed.

    3. When passing an object without ref, the object's data can be changed, but the reference to the object cannot be changed.

    void DoSomething(MyClass myClass)
    {
        myClass.myString = "ABC"   // the string is set to ABC
        myClass = new MyClass();   // has no affect - or may not even be allowed
    }
    
    1. When passing an object with ref, the object's data can be changed, and the reference to the object can be changed.
    void DoSomething(ref MyClass myClass)
    {
        myClass.myString = "ABC"   // the string is set to ABC
        myClass = new MyClass();   // the string will now be "" since myClass has been changed
    }
    

提交回复
热议问题