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

标签 c#

我在事件中创建了一个对象,现在我想要另一个事件来访问它。我该怎么做?

我在 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 中创建的 one 变量。

要实现这一点,您需要使 one 成为类变量,如下所示:

 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
}

关于c# - 如何在另一个事件中访问在一个事件中创建的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6182832/

相关文章:

C# UWP 应用程序调用了为不同线程编码的接口(interface)

C#:专用模板方法 - 错误:类型 '...' 已经使用相同的参数类型定义了一个名为 '...' 的成员

C# BinaryFormatter - 使用另一个命名空间中的对象反序列化

c# - 如何读取复制到 ASP .net 输出目录中的文件?

c# - 使用 REST 和 HTTPClient 在 SP2013 中创建文件夹

c# - Lucene.net 无法搜索 ".net"

c# - 在 LiveChart 中自定义起始索引

c# - 如何创建动态属性

c# - Bing map 运行时错误 Windows 8.1

C# 并行循环问题