-3

我正在尝试创建一个循环来添加 10 个项目,但只添加一个编号为 10 的项目。

List<Contact> listContact;

for (int cuantidade = 0; cuantidade < 10; cuantidade++)
{
    listContact = new List<Contact>(cuantidade)
    {
        new Contact()
        {
            Name =  cuantidade.ToString(),
            Number = cuantidade.ToString(),
        },
    };
}

this.listBoxNames.ItemsSource = listContact;

我究竟做错了什么?

4

2 回答 2

3

您需要在循环之前设置列表。使用您当前的代码,在每次迭代时,列表都会重新定义并重置......

于 2021-04-24T15:00:32.430 回答
3

尝试这个:

var contactList= new List<Contact>();

for (int cuantidade = 0; cuantidade < 10; cuantidade++)
{
    contactList.Add(new Contact
    {
        Name =  cuantidade.ToString(),
        Number = cuantidade.ToString(),
    });
}
this.listBoxNames.ItemsSource = contactList;
于 2021-04-24T14:13:11.687 回答