加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在另一个事件中访问在一个事件中创建的对象?

发布时间:2020-12-16 01:44:27 所属栏目:百科 来源:网络整理
导读:我在on事件中创建了一个对象,现在我想要另一个事件来访问它.我该怎么做呢? 我在Visual Studio 2010中这样做. 我有一个有三个按钮事件的表单.第一个按钮创建一个对象.我想要第二个按钮来使用该对象.我该怎么做呢? public void buttonCreate_Click(object se
我在on事件中创建了一个对象,现在我想要另一个事件来访问它.我该怎么做呢?

我在Visual Studio 2010中这样做.

我有一个有三个按钮事件的表单.第一个按钮创建一个对象.我想要第二个按钮来使用该对象.我该怎么做呢?

public void buttonCreate_Click(object sender,EventArgs e)
    {
        int size;
        int sizeI;
        string inValue;

        inValue = textBoxSize.Text;
        size = int.Parse(inValue);
        inValue = comboBoxSizeI.Text;
        sizeI = int.Parse(inValue);

        Histrograph one = new Histrograph(size,sizeI);
    }

    public void buttonAddValue_Click(object sender,EventArgs e)
    {
        int dataV = 0;
        string inValue;
        inValue = textBoxDataV.Text;
        dataV = int.Parse(inValue);
        one.AddData(dataV); //using the object
    }

解决方法

如果我正确地解析了你的问题,你想在buttonAddValue_Click中使用buttonCreate_Click中创建的一个变量.

要实现这一点,您需要创建一个类变量,如:

class MyForm : Form
 {
    Histogram one;

public void buttonCreate_Click(object sender,EventArgs e)
{
    int size;
    int sizeI;
    string inValue;

    inValue = textBoxSize.Text;
    size = int.Parse(inValue);
    inValue = comboBoxSizeI.Text;
    sizeI = int.Parse(inValue);

    one = new Histrograph(size,sizeI);  // NOTE THE CHANGE FROM YOUR CODE
}

public void buttonAddValue_Click(object sender,EventArgs e)
{
    int dataV = 0;
    string inValue;
    inValue = textBoxDataV.Text;
    dataV = int.Parse(inValue);
    one.AddData(dataV); //using the object
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读