我正在复习C#的知识。之前我使用过Java,Java中的引用传递是一种非常强大的工具,我真的很想在C#中也有这个功能。但是,我需要澄清的是是否有必要通过引用传递对象,以及是否存在需要使用它的场景?StackOverflow上已经有多个关于引用的问题,它们确实很有启发性,但我想知道是否存在需要通过引用传递对象的场景。让我附上代码以更好地说明。
class Program
{
public static void Update(int x) { x++; }
public static void Update(ref int x) { x++; }
public static void Update(Employee x) { x.msalary += 2000; }
public static void Update(ref Employee x) { x.msalary += 2000; } //Do we even need this method? Is there a scenario where we might need this?
static void Main(string[] args)
{
int a = 0;
Update(a);
Console.WriteLine("T1 " + a.ToString()); //a is still 0
Update(ref a);
Console.WriteLine("T2 " + a.ToString());//a is 1
Employee emp2 = new Employee("Brent", "1234", "Blue", 1000); //salary is 1000
Update(emp2.msalary);
Console.WriteLine("T3 " + emp2.msalary.ToString());//salary does not change.
Update(ref emp2.msalary);
Console.WriteLine("T4 "+emp2.msalary.ToString());//salary changes to 1001
Update(emp2);
Console.WriteLine("T5 " + emp2.msalary.ToString()); //This changes, as expected for objects.
Update(ref emp2);
Console.WriteLine("T6 " + emp2.msalary.ToString()); //This also changes. But is there a scenario where we might need this?
}
}
Update(ref Employee x)
方法可以执行x = new Employee()
,并且这个更改会在调用者中反映出来。 - canton7ref Employee
示例中没有对x
进行赋值,因此不需要这样做。 - Lee