将自定义对象添加到链接列表,列表已损坏

时间:2014-04-18 07:08:24

标签: c# linked-list

我有以下代码。

 private static Prints someprint = new Prints();
 private static LinkedList<Prints> LList = new LinkedList<Prints>(); 



public static void Main()
            {
                Console.Clear();
                someprint.ChangePrint(101.18, 101.16, 16, TimeSpan.Parse("00:00:20"), DateTime.Parse("4/8/2014 6:50:10 PM"));                
                LList.AddLast(someprint);

                someprint.ChangePrint(101.20, 101.10, 200, TimeSpan.Parse("00:00:20"), DateTime.Parse("4/8/2014 6:50:10 PM"));
                LList.AddLast(someprint);                

                someprint.ChangePrint(102.38, 102.36, 16, TimeSpan.Parse("00:00:40"), DateTime.Parse("4/8/2014 7:15:15 PM"));
                LList.AddLast(someprint);

                LinkedListNode<Prints> somenode = new LinkedListNode<Prints>(new Prints());

                somenode = LList.First;

                Console.WriteLine("LList");
                while (somenode != null)
                {
                    somenode.Value.PrintToScreen();
                    somenode = somenode.Next;
                }
                Console.ReadKey();

            }

这是我得到的输出。

LList
Sell Print
Start of Print=102.38
End of Print=102.36
Volume in Print=16
Time Spanned by Print=00:00:40
Time Stamp = 4/8/2014 7:15:15 PM
Sell Print
Start of Print=102.38
End of Print=102.36
Volume in Print=16
Time Spanned by Print=00:00:40
Time Stamp = 4/8/2014 7:15:15 PM
Sell Print
Start of Print=102.38
End of Print=102.36
Volume in Print=16
Time Spanned by Print=00:00:40
Time Stamp = 4/8/2014 7:15:15 PM

我似乎无法弄清楚为什么链表中的所有3张照片都是相同的。

我尝试了一个只有整数值的示例程序,但它确实有效。 我试过打印LList.Last.Value.PrintToScreen();在添加值之后,在该点打印正确的值。但我似乎无法检索链表。 任何人都可以解释一下。

1 个答案:

答案 0 :(得分:2)

现在,您将相同的Prints实例添加到列表中3次。您需要创建单独的实例。

private static LinkedList<Prints> LList = new LinkedList<Prints>();

public static void Main()
{
    Console.Clear();
    Prints someprint = new Prints();
    someprint.ChangePrint(101.18, 101.16, 16, TimeSpan.Parse("00:00:20"), DateTime.Parse("4/8/2014 6:50:10 PM"));
    LList.AddLast(someprint);

    someprint = new Prints();
    someprint.ChangePrint(101.20, 101.10, 200, TimeSpan.Parse("00:00:20"), DateTime.Parse("4/8/2014 6:50:10 PM"));
    LList.AddLast(someprint);

    someprint = new Prints();
    someprint.ChangePrint(102.38, 102.36, 16, TimeSpan.Parse("00:00:40"), DateTime.Parse("4/8/2014 7:15:15 PM"));
    LList.AddLast(someprint);

    LinkedListNode<Prints> somenode = new LinkedListNode<Prints>(new Prints());

    somenode = LList.First;

    Console.WriteLine("LList");
    while (somenode != null)
    {
        somenode.Value.PrintToScreen();
        somenode = somenode.Next;
    }
    Console.ReadKey();
}