C#将对象添加到List

时间:2016-02-03 16:34:04

标签: c# list sortedset

我刚刚开始学习c#,并且我正在创建一个程序的问题。

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

以下是我创建故障单并将其添加到List中的代码。

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();

似乎还清除了用于创建对象的所有先前ticketNumbers的列表

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

2 个答案:

答案 0 :(得分:6)

创建CTicket实例时,

firstTicket = new CTicket(i, ticketNumbers);

ticketNumbers是对传递给CTicket类的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#

答案 1 :(得分:0)

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

ticketNumbers = new List<int>();