.net ref关键字在引用类型上的使用

时间:2023-12-30 12:58:26
只接上干货。
namespace ConsoleApplication1
{
class Person
{
public string UserName { get; set; }
}
class Program
{
static void Main(string[] args)
{
var p = new Person {UserName = "Tom"};
ChangePersonData(p);
Console.WriteLine(p.UserName);// here will print "TOM" rather than "peter" ChangePersonDataByRef(ref p);
Console.WriteLine(p.UserName);// now it will print "peter".
Console.Read();
} static void ChangePersonData(Person per)
{
per = new Person{UserName = "peter"};
} static void ChangePersonDataByRef(ref Person per)
{
per = new Person {UserName = "peter"};
}
}
}

我们知道,如果我们不用ref或者out关键字,那函数参数就是实参的copy.
在ChangePersonData()中, 参数per就是局部变量p的copy。 在该函数中我们让per指向一个新new出来的Person对象,而对于原先的局部变量p来说是没有变化的,p这时还是指向了原有的Person对象。要想改变p指向的Person对象,我们就应该用ref或者out。因为ref和out会让我们按引用传递函数参数,也就是传递p本身而不是它的copy.