微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我在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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐