Reference type still needs pass by ref?

后端 未结 6 1614
一生所求
一生所求 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:49

    Every reference type is pass by value to a method call. So you can modify the data inside your instance because it is pointing to the same place, but if you want to modify the instance you should use ref

    public class Professor
    {
        public string _Name;
    
        public Professor(){}
    
        public Professor(string name)
        {
            _Name=name;
        }
    
        public void Display()
        {
            Console.WriteLine("Name={0}",_Name);
        }
    }
    
    public class Example
    {
        static int Main(string[] args)
        {
            Professor david = new Professor("David");
    
            Console.WriteLine("\nBefore calling the method ProfessorDetails().. ");
            david.Display();
            ProfessorDetails(ref david);
            Console.WriteLine("\nAfter calling the method ProfessorDetails()..");
            david. Display();
        }
    
        static void ProfessorDetails(ref Professor p)
        {
            //change in the name  here is reflected 
            p._Name="Flower";
    
            //Why  Caller unable to see this assignment 
            p=new Professor("Jon");
        }
    }
    

提交回复
热议问题