gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:17:20 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com