【问题标题】:How do I access an object created in one event in another event?如何在另一个事件中访问在一个事件中创建的对象?
【发布时间】:2011-05-31 12:06:46
【问题描述】:

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

【问题讨论】:

  • 你能说得更具体一点吗?
  • +1 让它变得更好。

标签: c#


【解决方案1】:

如果我正确解析了您的问题,您想在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
}

【讨论】:

    【解决方案2】:

    您可以通过使用私有变量而不是局部变量来完成此操作

    //Declare a private variable
    private object _myObject
    
    public void Event1Handler(object sender, EventArgs e)
    {
         //Create the object
         _myObject = CreateTheObject();
    }
    
    
    public void Event2Handler(object sender, EventArgs e)
    {
        //Use the object
        UseTheObject(_myObject);
    }
    

    【讨论】:

    • 我应该把“私有对象_myObject”这一行放在哪里?
    • 类声明主体内
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多