使用undefined Dictionary <Type,Type>作为方法的输入

kon*_*rad 3 c# dictionary

我试图定义一个在Windows窗体上填充ComboBox控件的通用方法.我通常使用Dictionary来填充我的组合框,将它们绑定到数据源.由于我有一些,我想创建一个方法,我可以调用键,值对的任意组合.这是我的尝试:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够这样称呼它:

PopulateDropdown(cbPrinters, this.inputData.Printers);其中 this.inputData.Printers是一个字典,键/值类型为字符串,字符串,但我也有其他组合,如字符串,int或字符串,对象.

我收到一个错误,无法将字符串,字符串转换为类型,类型.我怎样才能解决这个问题?

Ren*_*ogt 6

您需要使用泛型参数声明您的方法:

private void PopulateDropdown<TKey,TValue>(ComboBox control, Dictionary<TKey, TValue> dict)
{
}
Run Code Online (Sandbox Code Playgroud)