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

本文关键字:列表 已损坏 链接 自定义 对象 添加 | 更新日期: 2023-09-27 17:58:48

我有以下代码。

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

这是我得到的Ouput。

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

我似乎不明白为什么LinkedList中的3张照片都是一样的。

我尝试了一个只有整数值的示例程序,它成功了。

我尝试在添加值后打印List.Last.Value.PrintToScreen();,此时,它会打印正确的值。但我似乎无法检索链接列表。有人能解释一下吗?

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

现在您将同一个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();
}