通常,您希望避免将引用类型(如List<T>
)传递给ref
. 您可以传入List<T>
s 并调用您想要的任何方法,并且更改将很好地进行(如.Add()
, .Remove()
,.Sort()
等)。您只需要传入List<T>
一次(例如在构造函数中),即使您不使用ref
.
它的不同之处在于,当您传递List<T>
by时,您传递的是对变量ref
参数的引用(指针),而不是object。如果您想为变量分配一个新的,这只会产生影响。List<T>
我做了一个小程序来说明这种差异。
class Program
{
static void Main(string[] args)
{
List<int> listA = new List<int> { 1, 2, 3 };
List<int> listB = new List<int> { 1, 2, 3 };
Update(listA);
UpdateRef(ref listB);
Console.WriteLine("listA");
foreach (var val in listA)
Console.WriteLine(val);
Console.WriteLine("listB");
foreach (var val in listB)
Console.WriteLine(val);
}
static void Update(List<int> list)
{
list = new List<int>() { 4, 5, 6 };
}
static void UpdateRef(ref List<int> list)
{
list = new List<int>() { 4, 5, 6 };
}
}
这是程序产生的输出:
listA
1
2
3
listB
4
5
6
注意如何listB
包含新的List<T>
但listA
不包含。这是因为我们有一个对变量 listB
的引用。