C#传递泛型List报CS1503类型转换错误解决方案
C# 泛型方法填充下拉框触发CS1503类型转换错误解决
报错信息
传递泛型列表填充下拉框时遇到如下编译错误:
错误 CS1503 参数 2:无法从类型
System.Collections.Generic.List<PersonManager.Client>转换为System.Collections.Generic.List<System.Collections.Generic.List<PersonManager.Client>>
原始实现代码
public static bool FillDropDownBox<T>(ComboBox box, List<T> list, string displayMember, string valueMember) where T:List<T> { if (list.Count > 0) { box.Items.Clear(); box.Items.AddRange(list.ToArray()); box.DisplayMember = displayMember; box.ValueMember = valueMember; return true; } else { Debug("List is empty"); return false; } } public static List<Client> ClientList = new List<Client>(); public static void FillClientBox(ComboBox box, Control control) { if(FillDropDownBox<List<Client>>(box, ClientList, "Nickname", "Id")){ } }
错误原因
FillDropDownBox方法的泛型约束书写错误:where T:List<T>约束要求泛型参数T本身必须是List<T>类型,调用时显式指定T为List<Client>后,方法第二个参数要求的类型变为嵌套的List<List<Client>>,与传入的List<Client>类型的ClientList不匹配,触发类型转换错误。
修正后代码
public static bool FillDropDownBox<T>(ComboBox box, List<T> list, string displayMember, string valueMember) where T:class { if (list.Count > 0) { box.Items.Clear(); box.Items.AddRange(list.ToArray()); box.DisplayMember = displayMember; box.ValueMember = valueMember; box.SelectedIndex = 0; return true; } else { Debug("List is empty"); return false; } } public static void FillClientBox(ComboBox box, Control control) { if(FillDropDownBox(box, ClientList, "Nickname", "Id")) { } }
修正要点
- 将泛型约束从
where T:List<T>改为where T:class,仅限定T为引用类型即可,无需错误的嵌套列表约束 - 调用
FillDropDownBox时无需显式指定泛型参数,由编译器根据传入的ClientList自动推断T为Client类型 - 新增下拉框默认选中第一项的逻辑,优化交互体验
内容的提问来源于stack exchange,提问作者Nuvolari
相关产品推荐
相关产品推荐

