简体   繁体   English

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

[英]Cannot convert System.String to class type

I'm working with Polymorphism and I've run into a problem. 我正在使用多态性,但遇到了一个问题。

What I want to do is to call Animal class method GetEaterType() when list item is selected but I can't convert the animal class to Resultlst.SelectedItem; 我想要做的是在选择列表项时调用动物类方法GetEaterType() ,但是我无法将动物类转换为Resultlst.SelectedItem; This is how I tried: 这是我尝试的方法:

private void Resultlst_SelectedIndexChanged(object sender, EventArgs e)
        {
            Animal theanimal = (Animal) Resultlst.SelectedItem;
            // EaterTypetxt.Text = theanimal.GetEaterType().ToString();
        }

When I select an item on the list, I get error 当我在列表中选择一个项目时,出现错误

"Failed to convert an object of type System.String the type Assign_1.Animal" “无法将类型为System.String的对象转换为类型Assign_1.Animal”

UPDATE : How I populate the Resultlst with data 更新 :我如何用数据填充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());

            }

Don't call ToString() on your Animal when you add it to the list. 将其添加到列表时,请勿在Animal上调用ToString()

Use the DisplayMember property on the ListBox to specify which property of the Animal class should be displayed to the user. 使用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

Now you can cast the SelectedItem property to an Animal . 现在,您可以将SelectedItem属性转换为Animal

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

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

Since you've got multiple properties you'd like to display (which is why you're using ToString() in the first place), you could add a property to your class with just a "getter", and reference that: 由于您要显示多个属性(这就是为什么要首先使用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";

Addendum.. if you want to make the Description property overridable in derived classes, just make it virtual and override it when you want to: 附录..如果要使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."; }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将“ System.Object []”转换为类型“ System.String []” - Cannot convert 'System.Object[]' to the type 'System.String[]' 将字符串(System.String)转换为类型 - Convert string (System.String) to type TypeConverter无法从System.String转换 - TypeConverter cannot convert from System.String 反序列化对象时,无法将类型为System.String的对象转换为类型为System.Byte [] - Cannot convert object of type System.String to type System.Byte[] when deserializing object 无法将类型为“ System.String”的对象转换为类型为“ System.Collections.Generic.List`1” - Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1 绑定无法转换为 System.String 类型 - Binding cannot be converted to type System.String 无法创建类型为&#39;System.String&#39;的实例 - Cannot create instance of type 'System.String' 尝试解析JSON响应时出现错误-无法将类型为&#39;System.String&#39;的对象转换为类型&#39;&#39; - Getting error when trying to parse JSON Response - Cannot convert object of type 'System.String' to type '' asp.net json Web 服务发送数组错误无法将“System.String”类型的对象转换为“System.Collections.Generic.List`1[System.String]”类型 - asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]' 无法将System.String转换为System.DateTime - Cannot convert System.String to System.DateTime
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM