我正在使用多態,並且遇到問題。無法將System.String轉換爲類類型
我想要做的就是召喚獸類方法GetEaterType()
當選擇列表項,但我不能在動物類轉換爲Resultlst.SelectedItem;
這是我嘗試:
private void Resultlst_SelectedIndexChanged(object sender, EventArgs e)
{
Animal theanimal = (Animal) Resultlst.SelectedItem;
// EaterTypetxt.Text = theanimal.GetEaterType().ToString();
}
當我選擇一個名單上的項目,我得到錯誤
「未能轉換類型的對象System.String設置類型 Assign_1.Animal」
UPDATE:我如何填充Resultlst
數據
private void UpdateResults()
{
Resultlst.Items.Clear(); //Erase current list
//Get one elemnet at a time from manager, and call its
//ToString method for info - send to listbox
for (int index = 0; index < animalmgr.ElementCount; index++)
{
Animal animal = animalmgr.GetElementAtPosition(index);
//Adds to the list.
Resultlst.Items.Add(animal.ToString());
}
因爲顯然'SelectedItem'是一個字符串,而不是你的'Animal'類(或其衍生物)的一個實例。你能向我們展示你在哪裏用數據填充'Resultlst'的代碼? – 2015-04-02 02:30:20
顯示'Animal'類的代碼,包括其'ToString'實現。 – Igor 2015-04-02 02:36:57