2

我正在处理列表。我现在正在尝试确定 list first:nextlast. 我已经能够通过函数确定列表中项目的第一个和最后一个位置,getPostion并通过标签显示项目名称。我的表单中的三个按钮: ShowFirstItem ShowNextItem 和 ShowLastItem 在标签中显示相应的项目。我在显示下一个项目时遇到问题。我有特殊的方法来next调用GetNextTree。当我从内部ShowNextItem单击调用此方法时,我收到此错误:Cannot implicitly convert type 'TreeFarm.Form1.fruit_trees' to 'string'.如何避免此错误并显示当前指向的项目?

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

         public class ListForTrees {


             public fruit_trees GetNextTree() {
                 //save currently pointed tree
                 fruit_trees tree = this.current_tree;
                 if (tree != null) {
                     //move current_tree to the next tree, to be returned next time
                     current_tree = current_tree.next_tree;
                     //return saved tree object
                 }
                 return tree;
             }

         }
         private void ShowNextItem_Click(object sender, EventArgs e) {
             //Show Next Item
             labelSpecificTree.Text = mainlist.GetNextTree();
         }

     }
4

2 回答 2

2

这是因为您的 GetNextTree() 方法返回一个fruit_trees 对象,但您试图将该返回值设置为 ShowNextItem 内的一个字符串(labelSpecificTree 的 Text 属性)。您需要执行以下操作:

private void ShowNextItem_Click(object sender, EventArgs e)
{
    //Show Next Item
    labelSpecificTree.Text = mainlist.GetNextTree().ToString(); 
}
于 2012-12-14T02:14:04.637 回答
1

您需要将您的转换fruit_tree为字符串,并且您可能还需要考虑这种null情况:

private void ShowNextItem_Click(object sender, EventArgs e)
{
    //Show Next Item
    fruit_trees nextTree = mainlist.GetNextTree();
    if (nextTree == null)
    {
        labelSpecificTree.Text = "No more trees!";
    }
    else
    {
        labelSpecificTree.Text = nextTree.ToString();
    }
}

编辑:正如 MattSmith 指出的那样,也许您更愿意使用nextTree.GetTreeType来匹配您的其他方法。由你决定。

于 2012-12-14T02:12:13.463 回答