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)
}
How do I display both Name and AmountOfLegs in the listbox?
Like this: Steven 14
}
The ListBox
component displays what the ToString()
method returns. You can change the display by overriding the method
public class Cat : Animal // note you probably mistyped "class" here
{
public int AmountOfTeeth { get; set; }
public override string ToString()
{
return Name + " has " + AmountOfTeeth + " teeth"
}
}
I love to keep the data entities 'clean' and not to add display only related properties/methods. What I am usually do is creating local entity just for the display. Lets say AnimalDisplay which gets the base entity in its ctor. With the new entity I can add any prop I want just for the display, or override the ToString() in that mater and use this in the list.
Just another angle on this one...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.