相关疑难解决方法(0)

引用类型仍然需要通过ref?

请考虑以下代码(为简单起见,我没有遵循任何C#编码规则).

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(david);
        Console.WriteLine("\nAfter calling the method ProfessorDetails()..");
        david. Display();
    }

    static void ProfessorDetails(Professor p)
    {
        //change in the name  here is reflected 
        p._Name="Flower";

        //Why  Caller unable to see this assignment 
        p=new Professor("Jon");
    }
}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,输出是:

在调用方法之前,教授Details()......

姓名=大卫 …

c#

5
推荐指数
1
解决办法
6250
查看次数

标签 统计

c# ×1