【发布时间】:2010-11-25 19:06:41
【问题描述】:
考虑以下代码(为简单起见,我没有遵循任何 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");
}
}
正如预期的那样,输出是:
调用ProfessorDetails()方法之前...
姓名=大卫
调用ProfessorDetails()方法后...
名字=花
ProfessorDetails(Professor p) 中的调用p=new Professor("Jon"); 无效,即使它是引用类型。为什么我仍然需要使用ref 关键字来获得想要的结果?
【问题讨论】:
标签: c#