C# 的 new 操作存在bug吗?

5
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}

enter image description

有人能解释一下吗?

3个回答

14

这不是一个 bug,而是 C# 中 { ... } 初始化语法的结果。

该语法适用于任何具有 Add() 方法的集合类型。它所做的只是用 Add() 方法的一系列调用替换大括号中的序列。

在您的示例中,您首先在构造函数中使用前三个元素初始化值。然后,当您将 { 4, 5, 6 } 分配给属性时,它会再次使用这些值调用 Add()

如果要清除先前的内容,您需要使用 new 运算符进行分配,如下所示:

var listTest = new ListTest()
{
    MyList = new List<int> {4,5,6}
};

通过包含new运算符,您可以获得一个全新的对象,以及Add()值。


4
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

3

这个语法在构造函数完成后简单地调用.Add。结果你会先得到1,2,3,然后再依次添加4,5,6。


但它是赋值运算符。它等同于.add吗? - L.Tim
1
@L.Tim,它看起来像是一个赋值运算符,但实际上不是。它只是一种语法糖,用于在已初始化的集合中循环添加 {} 之间的项,逐个添加这些项。 - Massimiliano Kraus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接