Reference type still needs pass by ref?

后端 未结 6 1622
一生所求
一生所求 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 04:44

    You've got pass by reference and reference type mixed up.

    By changing p, you're not changing the thing that p points at, but where p itself is pointing at, so to speak. And because p has not been declared as ref, the reference (to the reference type) is passed by value, and the change to p is not reflected in the code calling ProfessorDetails. Changes to the instance p was pointing at are reflected (as that's a reference type). Would Professor have been a value type, not even those changes would be visible in the calling code.

提交回复
热议问题