Windows应用程序中是否有类似SESSION的东西?我想要存储一些值在不同的窗体之间保持持久化。
例如:第一个窗体有一些复选框,第三个窗体需要根据这些复选框进行处理。因此,我需要将选中的复选框存储在某个地方。
如果您需要在同一个应用程序中使用不同的表单,则只需在一个类上创建一些静态成员,它将在可执行文件的生命周期内保留。
您只能通过放置复选框的窗体上的属性来公开复选框的选中状态,并从第三个或进程窗体访问这些属性。
public partial class MainForm : Form {
// We assume we have let's say three CheckBoxes named chkFirst, chkSecond and chkThird
public bool IsFirstChecked { get { return chkFirst.Checked; } }
public bool IsSecondChecked { get { return chkSecond.Checked; } }
public bool IsThirdChecked { get { return chkThird.Checked; } }
// Calling this form from where these checked states will be processed...
// Let's suppose we have to click a button to launch the process, for instance...
private void btnLaunchProcess(object sender, EventArgs e) {
ProcessForm f = new ProcessForm();
f.Parent = this;
if (DialogResult.OK == f.ShowDialog()) {
// Process accordingly if desired, otherwise let it blank...
}
}
}
public partial class ProcessForm : Form {
// Accessing the checked state of CheckBoxes
private void Process() {
if ((this.Parent as MainForm).FirstChecked)
// Process according to first CheckBox.Checked state.
else if ((this.Parent as MainForm).SecondChecked)
// Process according to second CheckBox.Checked state.
else if ((this.Parent as MainForm).ThirdChecked)
// Process according to third CheckBox.Checked state.
}
}
internal class ApplicationState
{
// Store the selected checkbox values here, for example
public List<int> SelectedProductIds { get; }
// ... additional state ...
}
internal class EditOrderForm: Form
{
private ApplicationState applicationState;
public EditCustomerForm(ApplicationState applicationState) {
this.applicationState = applicationState;
}
// Rest of the code
}
你可以使用静态变量而不是实例 - 但这只是一些全局变量,会使你的代码更难以阅读和维护。
如果您想在执行会话之间以每个用户为基础存储数据,您应该考虑使用隔离存储(Isolated Storage)。