我有一个应用程序,其过程需要完成3个屏幕(表单)。我应该将我需要的变量从第一个表单传递给第二个表单(通过构造函数)和第三个表单,还是应该在第一个表单上创建一个公共访问器,我将从第二个和第三个表单访问?
这样做的正确方法是什么?
答案 0 :(得分:0)
正如评论中所提到的,我建议使用处理数据的控制器类。
基本上,一个在后台运行的对象,收集数据并根据需要显示表单,而不会让表单彼此了解任何内容。
基本上如此:
public class Controller {
private bool _formHasExited = false;
public static async void Main(string[] args) {
var form1DataObject = default(MyType1);
var form2DataObject = default(MyType2);
var form3DataObject = default(MyType3);
var form = default(Form);
// Display first form, collect data
using (form = new MyForm1()) {
form.Exited += (s, e) => _formHasExited = true;
await Task.Run(WaitForFormExit);
form1DataObject = form.Data;
}
// Reset _formHasExited
_formHasExited = false;
using (form = new MyForm2(form1DataObject.RequiredData)) {
form.Exited += (s, e) => _formHasExited = true;
await Task.Run(WaitForFormExit);
form2DataObject = form.Data;
}
// Reset _formHasExited
_formHasExited = false;
using (form = new MyForm3(form2DataObject.RequiredData)) {
form.Exited += (s, e) => _formHasExited = true;
await Task.Run(WaitForFormExit);
form3DataObject = form.Data;
}
// All data required has been obtained
// Do stuff with all data
}
void WaitForFormExit() {
// Example wait
while (!_formHasExited);
// Return
}
}
确保不阻止主线程,否则您的用户界面将无法响应。