我无法理解List<int>
背后的逻辑,因为它违反了一些基本规则。
List<int>
应该是值类型而不是引用类型。
List<int>
如果要在函数调用之间保持其值,则必须通过ref
关键字传递。这意味着它显示了类似于int的值类型行为。- 但是
List<int>
必须由new运算符初始化。此外,List<int>
也可能为null。这暗示了引用类型的行为。
可空类型则不同,因为它不需要由new运算符进行初始化。
我有什么地方看错了吗?
编辑 -
我应该在原始问题中发布代码。但是它在这里 -
namespace ConsoleApplication1
{
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;
}
}
}