将信息保存在散列表或数组中,然后输出
本文关键字:数组 然后 输出 列表 信息 保存 存在 | 更新日期: 2023-09-27 17:52:46
我正在用c#开发一个程序,我不知道该怎么处理这个问题。
在我的程序中,我有大量的复选框(Yes和No),当选择No时,会出现一个文本框,提示用户写注释,示例如下:
private void checkBox48_CheckedChanged(object sender, EventArgs e)
{
if (checkBox48.Checked == true)
{
// Create an instance of the dialog
frmInputBox input = new frmInputBox();
// Show the dialog modally, testing the result.
// If the user cancelled, skip past this block.
if (input.ShowDialog() == DialogResult.OK)
{
// The user clicked OK or pressed Return Key
// so display their input in this form.
problems = problems + "23. Check Outlet Drainage : " + input.txtInput.Text + Environment.NewLine;
this.txtProblems5.Text = problems;
txtProblems5.Visible = true;
}
// Check to see if the dialog is still hanging around
// and, if so, get rid of it.
if (input != null)
{
input.Dispose();
}
}
}
然而,我暂时将用户输入写入名为problems
的String
。我希望将这些值分别保存在不同的位置。
哈希表或数组合适吗?(例如txtInput.Text = Problems[40]
)
数组或哈希表都可以。哈希表可能对开发人员更友好,并且可能占用更小的内存。下面是一个小例子:
private Dictionary<int, string> problems = new Dictionary<int, string>;
// add key value pair
problems.Add(42, "your problem here");
// get value
string value = "";
if (problems.TryGetValue(42", out value))
{
// the key was present and the value is now set
}
else
{
// key wasn't found
}
如果使用数组,则意味着必须按照示例为每个文本框创建条目。
出于偏好,我可能会使用dictionary<string,string>
,其中键是控件名称。
然后,我的textbox
值可以是:
txtProblem1.text = dictionary.ContainsKey(txtProblem1.Name) ? dictionary[txtProblem1.Name] : "";