【发布时间】:2014-10-22 08:02:33
【问题描述】:
您好,我想创建一个动态通用输入框函数,它允许用户从输入列表中选择一个输入,然后将其返回。对于我想使用字典的项目列表。
对于声明,我的思路如下:
public static DialogResult InputBox<KeyType, ValueType>(string aTitle, string aPromptText, Dictionary<KeyType, ValueType> aDictionary, ref KeyValuePair<KeyType, ValueType> aReturnPair)
我已经有两个类似的函数,一个用于日期,一个用于字符串。
但我想知道字典是否可能? 我如何处理铸件?我是否也必须传递键和值的类型,或者我可以在运行时检索它吗?
也可以指定“函数”来检索用于显示的名称例如我有以下结构:
public struct Person
{
public int Age;
public string Name;
public string Surname;
}
如何告诉函数使用 Person.Surname 进行显示?
示例用法:
Dictionary<int, Person> Persons = new Dictionary<int,Person>();
KeyValuePair<int, Person> lPair= new KeyValuePair<int,Person>
DialogResult dialogResult = DialogResult.Cancel
While (dialogResult == DialogResult.Cancel)
{
dialogResult = CustomForm.InputBox<int, Person>("title", "prompt", Persons, ref lPair, Person.Surname);
}
字符串输入函数
public static DialogResult InputBox(string aTitle, string aPromptText, ref string aValue, Boolean aPassword = false )
{
Form lForm = new Form();
Label lLabel = new Label();
TextBox lTextBox = new TextBox();
Button lButtonOk = new Button();
Button lButtonCancel = new Button();
lForm.Text = aTitle;
lLabel.Text = aPromptText;
lTextBox.Text = aValue;
if (aPassword)
{
lTextBox.PasswordChar = '*';
}
lButtonOk.Text = "OK";
lButtonCancel.Text = "Cancel";
lButtonOk.DialogResult = DialogResult.OK;
lButtonCancel.DialogResult = DialogResult.Cancel;
lLabel.SetBounds(9, 20, 372, 13);
lTextBox.SetBounds(12, 36, 372, 20);
lButtonOk.SetBounds(228, 72, 75, 23);
lButtonCancel.SetBounds(309, 72, 75, 23);
lLabel.AutoSize = true;
lTextBox.Anchor = lTextBox.Anchor | AnchorStyles.Right;
lButtonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
lButtonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
lForm.ClientSize = new Size(396, 107);
lForm.Controls.AddRange(new Control[] { lLabel, lTextBox, lButtonOk, lButtonCancel });
lForm.ClientSize = new Size(Math.Max(300, lLabel.Right + 10), lForm.ClientSize.Height);
lForm.FormBorderStyle = FormBorderStyle.FixedDialog;
lForm.StartPosition = FormStartPosition.CenterScreen;
lForm.MinimizeBox = false;
lForm.MaximizeBox = false;
lForm.AcceptButton = lButtonOk;
lForm.CancelButton = lButtonCancel;
DialogResult dialogResult = lForm.ShowDialog();
aValue = lTextBox.Text;
return dialogResult;
}
【问题讨论】:
-
哪里需要用到字典?
-
这个想法是覆盖字符串函数,仅用于字典。我希望能够给函数一个字典,然后它会提示用户输入一个部分。它适用于我正在创建的用于我们所有应用程序的库。这就是为什么我想要动态的键和值
-
请检查我的编辑
标签: c# generics dictionary casting