1

我目前正在处理程序开始时加载的项目列表。我正在尝试确定每个项目的位置。所以我有First显示第一个项目(当前)的按钮,Next它在第一个(Current.Next)之后显示以下项目,Last它应该显示最后一个项目,但它根本不显示任何内容。在按钮单击名为 的标签后显示结果labelSpecificTree。我尝试在Last按钮单击行内设置中断Current = Trees.Last;以查看结果,但没有给我任何具体细节。如何通过标签显示列表中的最后一项?

代码

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        ListOfTrees Trees = new ListOfTrees();
        FruitTrees Tree;
        FruitTrees Current;

        double Total;



        public class ListOfTrees
        {
            private int size;

            public ListOfTrees()
            {
                size = 0;
            }

            public int Count
            {
                get { return size; }
            }

            public FruitTrees First;
            public FruitTrees Last;

             public int Add_Initialize(FruitTrees NewItem)
             {
                 NewItem.Next = First;
                 First = NewItem;
                 Last = First.Next;

                 if (Last == null)
                 {
                     Last = First;
                 }

                 return size++;
             }

            public int Add(FruitTrees newItem)
            {
                if (First == null)
                    return Add_Initialize(newItem);

                FruitTrees item = First;
                while (item.Next != null)
                {
                    item = item.Next;
                }

                item.Next = newItem;
                return size++;
            }



        }




        public void Clear()
        {
            textBoxType.Clear();
            textBoxHeight.Clear();
            textBoxPrice.Clear();
            textBoxStock.Clear();
        }


        public void Current_Tree()
        {
            Current = Trees.First;
            labelSpecificTree.Text = Current.Type.ToString();
        }


        private void Form1_Load_1(object sender, EventArgs e)
        {

            Tree = new FruitTrees();
            Tree.Stock = 15;
            Tree.Type = "Pear";
            Tree.Price = 49.99;
            Tree.Height = 20;
            Total += Tree.Price * Tree.Stock;
            Trees.Add(Tree);

            ShowTrees();
            Current_Tree();
        }


        private void buttonLast_Click(object sender, EventArgs e)
        {
            Current = Trees.Last;
            labelSpecificTree.Text = Current.Type.ToString();
        }
    }
}
4

2 回答 2

2

在您的代码中,当您使用 Add 添加新项目时,您不会移动 Last。试试这个:

public int Add(FruitTrees newItem)
{
    if (First == null)
    return Add_Initialize(newItem);

    FruitTrees item = First;
    while (item.Next != null)
    {
        item = item.Next;
    }

    item.Next = newItem;
    Last = newItem;
    return size++;
}
于 2012-12-11T16:27:13.880 回答
1

您没有在 ListOfTrees.Add() 方法中设置 Last 。

尝试在您的return size++;陈述之前添加此内容:

Last = newItem;
于 2012-12-11T16:27:03.130 回答