无法将System.String转换为类类型

时间:2015-04-02 02:20:09

标签: c#

我正在使用多态性,我遇到了一个问题。

我想要做的是在选择列表项时调用Animal类方法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“

更新:我如何使用数据填充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());

            }

1 个答案:

答案 0 :(得分:3)

ToString()添加到列表中时,请勿致电Animal

使用DisplayMember上的ListBox属性指定应向用户显示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()的原因),您可以只使用“getter”为您的类添加属性,并参考:

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."; }
    }
}