Passing by ref?

后端 未结 4 1025
无人共我
无人共我 2021-02-08 11:53

I am still confused about passing by ref.

If I have a Cache object which I want to be accessed/available to a number of objects, and I inject it using constructor inject

4条回答
  •  梦谈多话
    2021-02-08 12:17

    Use the 'ref' keyword when the you need to modify what the reference is pointing to. When you pass a reference type into a method it is passed by value, but the value is a copy of that reference which is passed to the method. This means that you can change the general state (i.e., properties/fields) of the referred to object, but if you attempt to change what the reference points to you will only affect the copy.

    For example, given this method...

    private void Foo( MyClass obj )
    {
        obj = new MyClass( );
        obj.SomeProperty = true;
    }
    

    We can pass in the argument and then see if it was affected:

    MyClass test = new MyClass( );
    test.SomeProperty = false;
    Foo( test );
    Console.WriteLine( test.SomeProperty );  // prints "False"
    

    Now, if we had defined the method using the 'ref' keyword...

    private void Foo( ref MyClass obj )
    {
        obj = new MyClass( );
        obj.SomeProperty = true;
    }
    

    The output would be "True", because the actual reference was passed to the method, not a copy. We changed what that reference points to within the function and we see the effects of those changes.

    You are just creating a new pointer to the object on the heap when you omit the 'ref' keyword. If you change one pointer you will not change the other.

    ...

    So, to answer your question; no, you do not need to use the 'ref' keyword to change the state of your single Cache object when it is passed to a method.

提交回复
热议问题