Reference type still needs pass by ref?

后端 未结 6 1621
一生所求
一生所求 2020-11-29 04:33

Consider the following code (for simplicity, I did not follow any C# coding rules).

public class Professor
{
    public string _Name;
    
    public Professo         


        
6条回答
  •  日久生厌
    2020-11-29 05:02

    The actual value of p is a reference to the same professor instance as david. Any calls you make on that reference are dereferenced as calls to the same instance as would calls made on david be. However, p is a copy of that reference, it's not the same as david value.

    Thus, when you do p = new Professor(), you are changing the value of the reference variable to point to a new instance. However, that does not modify the david reference, which still points to the old instance.

    If you were to pass p as ref,the value of p would be a reference to the david reference variable. Modifying it would actually modify the david value to point to a new instance.

提交回复
热议问题