繁体   English   中英

在窗体中加载窗体时创建对象

[英]Create an object when a form loads in windows forms

我将编写一个项目来展示这样的 AVL 树: pic

我有两个类:AVLTree 和 TreePresantation。 问题是我不能在 Button_Click 中使用我的类的方法

  private void Form1_Load(object sender, EventArgs e)
    {
        AVLTree avltree = new AVLTree();
        TreePresantation treePresantation = new TreePresantation(avltree);
    }

    private void BtnPut_Click(object sender, EventArgs e)
    {
        if ((txtPutKey.Text == null) || (txtPutValue.Text == null))
        {
            txtMessage.Text = "Key or Value cannot be empty!";
        }
        else
        {
            treepresantation.Put(Convert.ToInt32(txtPutKey.Text), txtPutValue.Text);
        }
    }

btnPut_Click 中的“treepresantation”带有红色下划线,错误是:错误 CS0103 当前上下文中不存在名称“treepresantation”

谁能帮我?

我似乎找不到副本,即使它似乎应该有一个,所以就在这里。

您的变量与您调用它们的范围不在同一范围内,因此您无法调用它们。

这是解决问题的一种方法:

public YourClass {

    private AVLTree avltree;
    private TreePresantation treePresantation;

    private void Form1_Load(object sender, EventArgs e)
    {
        avltree = new AVLTree();
        treePresantation = new TreePresantation(avltree);
    }

    private void BtnPut_Click(object sender, EventArgs e)
    {
        if ((txtPutKey.Text == null) || (txtPutValue.Text == null))
        {
            txtMessage.Text = "Key or Value cannot be empty!";
        }
        else
        {
            treepresantation.Put(Convert.ToInt32(txtPutKey.Text), txtPutValue.Text);
        }
    }
}

但正如 Thomas 指出的那样,您应该找到 C# 教程来了解基础知识。

希望这可以帮助。

编辑

如果您不需要在Form1_Load之外的其他地方访问avltree ,您可以将其从本地类属性中删除。

public class Form1
{
    private TreePresantation treePresantation = null;

    private void Form1_Load(object sender, EventArgs e)
    {
        AVLTree avltree = new AVLTree();
        treePresantation = new TreePresantation(avltree);
    }

    private void BtnPut_Click(object sender, EventArgs e)
    {
        if ((txtPutKey.Text == null) || (txtPutValue.Text == null))
        {
            txtMessage.Text = "Key or Value cannot be empty!";
        }
        else
        {
            treepresantation.Put(Convert.ToInt32(txtPutKey.Text), txtPutValue.Text);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM