我的int
在dataStorage.cs
中的单独类中声明,在此操作完成后会丢失其值:
private void button1_Click(object sender, EventArgs e)
{
dataStore dataStore = new dataStore();
dataStore.position = Convert.ToInt32(numericUpDown1.Value);
} // <= right here the value is reset to 0
我想要做的是,在表单之间传递值。但是当另一个表单开始其进程时,我的dataStorage.position
会丢失其值并重置为“0”。
如何在表单之间正确传递值?
答案 0 :(得分:5)
这是因为您正在创建一个本地存储变量,该变量会立即超出范围。
将其声明为表单类的一部分:
public class MyForm : Form
{
public dataStore _dataStore = new dataStore();
public MyForm() { }
private void button1_click(Object sender, EventArgs e)
{
_dataStore.position = Convert.ToInt32(numericUpDown1.Value);
}
}
答案 1 :(得分:2)
你没有对dataStore
做过任何事情。听起来您想为position
的实例设置dataStorage
的值,而您实际上并未使用它。您需要将dataStorage
的实例设置为您在该按钮中创建的实例,以便保留其值。
答案 2 :(得分:2)
实际上是期望这种行为。 实例化对象时,它只在其创建的上下文中具有范围。
private void button1_Click(object sender, EventArgs e)
{
dataStore dataStore = new dataStore();
dataStore.position = Convert.ToInt32(numericUpDown1.Value);
} // When this function returns, dataStore no longer exists!
在这种情况下,您的dataStore对象仅存在于按钮单击处理程序内。
您要做的是将DataStore声明为您的类的私有成员,然后在Click处理程序中指定值。
private dataStore dataStore = new dataStore();
private void button1_Click(object sender, EventArgs e)
{
dataStore.position = Convert.ToInt32(numericUpDown1.Value);
} // <= right here the value is reset to 0
此外,C#中的实际类名应该为每个单词(PascalCase)设置大写字母,而不是小写的第一个字母,后跟大写的剩余单词(camelCase):
class DataStore { }
...
private DataStore dataStore = new DataStore();
答案 3 :(得分:2)
您不会将值保留在任何持久的位置。以下是您正在做的事情的解释:
private void button1_Click(object sender, EventArgs e)
{
// You've called a function, in this case a click handler
// Here you create an instance of `dataStore`
// This instance exists *only* within the scope of this function
dataStore dataStore = new dataStore();
// Here you set a value on that instance
dataStore.position = Convert.ToInt32(numericUpDown1.Value);
}
// Now that the function has ended, any variables which were declared
// within the scope of the function are now out of scope, and removed
// from memory.
此代码中不清楚的是值应该如何保留。有很多选择:
dataStore
对象提交到持久性并在其他地方检索它。dataStore
实例作为方法参数传递给您接下来要呼叫的任何内容。dataStore
声明为此表单的类级别成员,并在其他方法中引用它。可能是(但是,我们无法从此代码中确切地知道)您想要第四个选项。在您的表单上看起来像这样:
public class YourForm : Form
{
private dataStore dataStore = new dataStore();
private void button1_Click(object sender, EventArgs e)
{
dataStore.position = Convert.ToInt32(numericUpDown1.Value);
}
private void YourOtherMethod()
{
// dataStore.position will have a value after the button
// click handler is executed
}
}
这里的要点是根据对象实例进行思考。将类视为对象的“蓝图”。创建new
对象时,您将基于该蓝图构建实例。该实例现在在系统中是唯一的,如果您需要在代码中的其他位置访问它,那么该实例需要以某种方式在系统中传递。