2015-04-02 270 views
0

我正在使用多態,並且遇到問題。無法將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()); 

      } 
+2

因爲顯然'SelectedItem'是一個字符串,而不是你的'Animal'類(或其衍生物)的一個實例。你能向我們展示你在哪裏用數據填充'Resultlst'的代碼? – 2015-04-02 02:30:20

+1

顯示'Animal'類的代碼,包括其'ToString'實現。 – Igor 2015-04-02 02:36:57

回答

3

當你把它添加到列表中別叫ToString()Animal

使用ListBox上的DisplayMember屬性來指定應向用戶顯示Animal類的哪個屬性。

for (int index = 0; index < animalmgr.ElementCount; index++) 
{ 
    Animal animal = animalmgr.GetElementAtPosition(index); 

    Resultlst.Items.Add(animal); // add the Animal instance; don't call ToString() 
} 

Resultlst.DisplayMember = "Name"; // whatever property of your class is appropriate 

現在你可以在SelectedItem財產強制轉換爲Animal

private void Resultlst_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    Animal theanimal = (Animal)Resultlst.SelectedItem; 

    EaterTypetxt.Text = theanimal.GetEaterType().ToString(); 
} 

既然你有多個屬性,你想顯示(這就是爲什麼你會在第一時間使用ToString()),你可以將屬性添加到您的類只是一個「吸氣」,並說明:

public class Animal 
{ 
    public string Name { get; set; } 
    public Color Color { get; set; } 

    public string Description 
    { 
     get { return string.Format("{0} {1}", Color.Name, Name); } // Red Dog, Purple Unicorn 
    } 
} 

Resultlst.DisplayMember = "Description"; 

編..如果你想使Description屬性在派生類中重寫,只是讓虛擬和覆蓋它,當你想:

public class Animal 
{ 
    public string Name { get; set; } 
    public Color Color { get; set; } 

    public virtual string Description 
    { 
     get { return string.Format("{0} {1}", Color.Name, Name); } 
    } 
} 

public class Dog : Animal 
{ 
    public override string Description 
    { 
     get { return base.Description; } 
    } 
} 

public class Cat : Animal 
{ 
    public override string Description 
    { 
     get { return "I'm a cat. I'm special."; } 
    } 
} 
+0

這都假設他的Resultlst類是'Animal'類型,而不是字符串類型。 – dstepan 2015-04-02 02:43:39

+0

但這不僅僅是我想在列表中顯示的一個屬性。它們很多,'ToString'將它們很好地分開。 是否沒有其他方法通過使用多態性來調用子類? – 2015-04-02 02:45:34

+0

您是否可以選擇僅使用「getter」創建一個屬性,並將您希望顯示的所有值連接起來,就像您當前在'ToString()'中執行的操作一樣? – 2015-04-02 02:47:33

相關問題