public class ListTest
{
public List<int> MyList;
public ListTest()
{
MyList = new List<int> { 1, 2, 3 };
}
}
var listTest = new ListTest()
{
MyList = {4,5,6}
};
你知道listTest.MyList
的值吗?
它将是{1,2,3,4,5,6}
有人能解释一下吗?
public class ListTest
{
public List<int> MyList;
public ListTest()
{
MyList = new List<int> { 1, 2, 3 };
}
}
var listTest = new ListTest()
{
MyList = {4,5,6}
};
你知道listTest.MyList
的值吗?
它将是{1,2,3,4,5,6}
有人能解释一下吗?
这不是一个 bug,而是 C# 中 { ... }
初始化语法的结果。
该语法适用于任何具有 Add()
方法的集合类型。它所做的只是用 Add()
方法的一系列调用替换大括号中的序列。
在您的示例中,您首先在构造函数中使用前三个元素初始化值。然后,当您将 { 4, 5, 6 }
分配给属性时,它会再次使用这些值调用 Add()
。
如果要清除先前的内容,您需要使用 new
运算符进行分配,如下所示:
var listTest = new ListTest()
{
MyList = new List<int> {4,5,6}
};
通过包含new
运算符,您可以获得一个全新的对象,以及Add()
值。
var listTest = new ListTest() // This line will first call constructor of ListTest class .
//As constructor adds 1,2,3 in list MyList will have 3 recrods
{
MyList = {4,5,6} // Once you add this statement this will add 3 more values in the list .
// So instead of creating new list it will Add 3 elements in existing list
};
//Hence total 6 records will be there in the list
这个语法在构造函数完成后简单地调用.Add
。结果你会先得到1,2,3,然后再依次添加4,5,6。
{}
之间的项,逐个添加这些项。 - Massimiliano Kraus