使用未定义的Dictionary< Type,Type>作为方法的输入 [英] use undefined Dictionary<Type, Type> as an input to method
问题描述
我正在尝试定义一种用于在Windows窗体上填充ComboBox控件的通用方法.我通常使用Dictionary通过将组合框绑定到数据源来填充组合框.由于只有少数几个,因此我想创建一种方法,可以仅对键,值对的任意组合进行调用.这是我的尝试:
I am trying to define a generic method for populating ComboBox controls on Windows Forms. I am usually using Dictionary to populate my combo boxes by binding them to the Data Source. Since I have a handful of those, I wanted to make a method that I can just call on any combination of a key, value pairs. Here's my attempt:
private void PopulateDropdown(ComboBox control, Dictionary<Type, Type> dict)
{
if (dict.Count > 0)
{
control.DataSource = new BindingSource(dict, null);
control.DisplayMember = "Key";
control.ValueMember = "Value";
}
}
我希望能够这样称呼它:
I would like to be able to call it like so:
PopulateDropdown(cbPrinters, this.inputData.Printers);
其中, this.inputData.Printers
是字典,键/值类型为字符串,字符串,但是我还有其他组合,例如字符串,整数或字符串,对象.
PopulateDropdown(cbPrinters, this.inputData.Printers);
where this.inputData.Printers
is a Dictionary with key/value types as string, string but I also have other combinations like string, int or string,object.
我遇到了无法将字符串,字符串转换为Type,Type的错误.我怎样才能解决这个问题?
I am getting an error that cannot convert string, string to Type, Type. How can I fix this?
推荐答案
您需要使用通用参数声明方法:
You need to declare your method with generic parameters:
private void PopulateDropdown<TKey,TValue>(ComboBox control, Dictionary<TKey, TValue> dict)
{
}
这篇关于使用未定义的Dictionary< Type,Type>作为方法的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!