我正在嘗試傳遞一個通用串列,但出現以下錯誤:
錯誤 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")){
}
}
解決方案代碼:
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"))
{
}
}
uj5u.com熱心網友回復:
在你的方法中:
public static bool FillDropDownBox<T>(ComboBox box, List<T> list, string displayMember, string valueMember) where T:List<T>
T指定填充的物件的型別,List并且您將其限制為串列串列!
因此,當您呼叫它時,您將其指定為整個串列,但您只傳遞了一個普通串列,我假設它是List<Client>:
FillDropDownBox<List<Client>>(box, ClientList, "Nickname", "Id")
所以編譯器需要一個串列串列!那是你的問題。
將限制更改為where T:class
實際上,您應該能夠完全洗掉顯式宣告,并且編譯器可以從傳遞的串列中推斷出型別ClientList
public static void FillClientBox(ComboBox box, Control control)
{
if(FillDropDownBox(box, ClientList, "Nickname", "Id")){
}
uj5u.com熱心網友回復:
你只需要這樣做:
public static bool FillDropDownBox<T>(ComboBox box, List<T> list, string displayMember, string valueMember)
{
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 void FillClientBox(ComboBox box, Control control)
{
if (FillDropDownBox<Client>(box, ClientList, "Nickname", "Id"))
{
}
}
因為引數是 aList<T>你不需要約束T。
當你打電話時,FillDropDownBox你只需要指定型別 - 如果你指定它,List<Client>那么你說list引數是List<List<Client>>.
uj5u.com熱心網友回復:
在您的FillDropDownBox<List<Client>>方法中,您必須具有如下引數:
List<T> listOfClients,
所以你必須把它寫到:
T listOfClients,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485405.html
上一篇:java.lang.NoSuchMethodError:com.mongodb.internal.operation.SyncOperations.aggregate
