可能重复:
c#中的List <int>
我有以下程序.我对输出感到困惑.
行 -
Console.WriteLine(listIsARefType.Count)打印0而不是1.任何想法为什么?
class Program
{
static void Main(string[] args)
{
ListTest d = new ListTest();
d.Test();
}
}
class ListTest
{
public void ModifyIt(List<int> l)
{
l = returnList();
}
public void Test()
{
List<int> listIsARefType = new List<int>();
ModifyIt(listIsARefType);
Console.WriteLine(listIsARefType.Count); // should have been 1 but is 0
Console.ReadKey(true);
}
public List<int> returnList()
{
List<int> t = new List<int>();
t.Add(1);
return t;
}
}
Run Code Online (Sandbox Code Playgroud)
.Net中的所有内容都默认按值传递,甚至是引用类型.与引用类型的区别在于它是通过值传递的引用本身.因此,当您调用该ModifyIt()函数时,您将该函数的引用副本传递给该函数.该函数然后更改复制的引用.原始列表引用仍然完好无损,列表不变.你的代码应该是这样的:
void ModifyIt(List<int> t)
{
t.Add(1);
}
Run Code Online (Sandbox Code Playgroud)
你会看到现在列表确实发生了变化.你也可以这样做:
void ModifyIt(ref List<int> t)
{
t = returnList();
}
Run Code Online (Sandbox Code Playgroud)
但是,你应该赞成前者与后者的风格.如果你已经有类似returnList()函数的东西,并且你真的需要一个函数来将这些项添加到现有列表中,那就这样做:
void ModifyIt(List<int> t)
{
t.AddRange(returnList());
}
Run Code Online (Sandbox Code Playgroud)