C# 添加对象到列表

C# Adding objects to List

我刚开始学习 c#,我正在创建的程序遇到了一个小问题。

我正在创建一个程序,该程序将创建多张乐透彩票,每张彩票都有一个 ID 和六个随机生成的号码。

这是我创建票证并将它们添加到列表的代码。

Random random = new Random();// Random number generator
for (int i = 0; i < 1000; i++)
{
    do
    {
    int randomNumber = random.Next(1, 42);// Create randoms numbers between 1 and 42
    ticketNumbers.Add(randomNumber);// Add the random numbers to the ticketNumbers SortedSet                  
    }
    while (ticketNumbers.Count< 6);// Stop Adding once the six numbers is reached

    CTicket firstTicket;
    firstTicket = new CTicket(i, ticketNumbers);// Create ticket object pass i's current value as the ticket id and pass the ticketNumbers sorted set as the ticket numbers
    ticketList.Add(firstTicket);// Add the firstTicket object to the ticketList
    ticketNumbers.Clear();// clear the ticketNumbers list to start again for the next ticket
}

CTicket.Printlist(ticketList);

这是我打印列表的函数:

public static void Printlist(List<CTicket> ticketList)
{
    foreach (CTicket mytick in ticketList)
    {
        Console.WriteLine("Ticket ID = {0} ", mytick.m_ticketID);

        foreach (int val in mytick.m_ticketNumbers)
        {
            Console.WriteLine(val);
        }                            
    }
}

我的问题是当我创建一个票证对象并将其添加到列表时,打印函数将只显示 ID 而不是数字。我已将问题追溯到以下内容:

ticketNumbers.Clear();

似乎也正在清除列表中用于创建对象的所有先前票号

有人可以向我解释为什么会这样吗?

当您创建 CTicket 实例时,

firstTicket = new CTicket(i, ticketNumbers);

ticketNumbers 是对传递给 CTicket class 的 SortedSet 实例的引用。您的所有 CTicket 实例都包含对同一 SortedSet 实例的引用的副本。当您清除它时,所有 CTickets 将引用相同的空集。

解决方案是为每个 CTicket 创建一个新的 ticketNumbers 集,然后每个 CTicket 将包含对不同集的引用。

Random random = new Random();// Random number generator
for (int i = 0; i < 1000; i++)
{
    SortedSet<int> ticketNumbers = new SortedSet<int>();
    do
    {
    int randomNumber = random.Next(1, 42);// Create randoms numbers between 1 and 42
    ticketNumbers.Add(randomNumber);// Add the random numbers to the ticketNumbers SortedSet                  
    }
    while (ticketNumbers.Count< 6);// Stop Adding once the six numbers is reached

    CTicket firstTicket;

    firstTicket = new CTicket(i, ticketNumbers);// Create ticket object pass i's current value as the ticket id and pass the ticketNumbers sorted set as the ticket numbers
    ticketList.Add(firstTicket);// Add the firstTicket object to the ticketList
    ticketNumbers.Clear();// clear the ticketNumbers list to start again for the next ticket
}

CTicket.Printlist(ticketList);

查看此处了解更多信息information on passing reference type parameters in C#

@sean 解释说你必须重新初始化列表变量而不是清除

ticketNumbers = new List<int>();