Reference to reference in C#?

前端 未结 6 1587
花落未央
花落未央 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条回答
  •  -上瘾入骨i
    2021-02-05 19:16

    The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type.

    Passing a type by reference enables the called method to modify the object refered by the parameter or to change the storage location of the parameter.

    static void Main()
    {
        Foo item = new Foo("aaa");
        GetByReference(ref item);
        Console.WriteLine(item.Name)
    }
    static void ChangeByReference(ref Foo itemRef)
    {
        itemRef = new Foo("bbb");
    }
    

    this will actually print "bbb", because in this case you did not changed the objects values but you changed the object itself

提交回复
热议问题