C# 如何在listbox中显示基类和子类的属性

C# 如何在listbox中显示基类和子类的属性,c#,C#,如何在列表框中同时显示名称和数量 像这样:史蒂文14 }列表框组件显示ToString()方法返回的内容。可以通过重写该方法来更改显示 public class Animal { public string Name {get;set;} } public string Cat : Animal { public int AmountOfTeeth {get;set;} } //In Form.cs: public void showAnimal(){ var ani

如何在列表框中同时显示名称和数量

像这样:史蒂文14


}列表框
组件显示
ToString()
方法返回的内容。可以通过重写该方法来更改显示

public class Animal
{

 public string Name {get;set;}


}

public string Cat : Animal
{

 public int AmountOfTeeth {get;set;}

}


//In Form.cs:

public void showAnimal(){


 var animalList = _animalManager.GetAnimals();


foreach(var animal in animalList)
{

     animalListbox.Items.Add(animal)
}

我喜欢保持数据实体“干净”,不添加仅显示相关属性/方法。 我通常只为显示创建本地实体。比如说AnimalDisplay,它在其ctor中获取基本实体。有了新的实体,我可以添加任何只用于显示的道具,或者覆盖该实体中的ToString()并在列表中使用它


这只不过是另一个角度

什么类型的动物学家?GetAnimals()返回列表谢谢!它起作用了!我想我必须重写例如Dog类中的ToSTring()方法等等。。。
public class Cat : Animal // note you probably mistyped "class" here
{
    public int AmountOfTeeth { get; set; }
    public override string ToString()
    {
        return Name + " has " + AmountOfTeeth + " teeth"
    }
}