gpt4 book ai didi

c# - 从 C# 中的抽象列表调用对象特定方法

转载 作者:行者123 更新时间:2023-11-30 20:00:41 25 4
gpt4 key购买 nike

我有一个像这样的抽象类列表

List<Animal> animalList = new List<Animal>();

我通过做遍历列表

foreach(Animal a in animalList.Values){
if(a is Monkey){
//Call monkey specific method
a.PeelBanana() //This is essentially what I would like to be able to do
}
else if(a is Giraffe){
//Call a method specific to Giraffe
}

}

所以动物共享共同的功能,如 eat() 和 sleep() 但我想知道是否有办法调用,例如,从猴子类中调用 PeelBanana(),一种在所有方法中都不存在的方法Animal 类的派生。

最佳答案

我建议你把Animal做成抽象类,让MonkeyGiraffe等动物实现通用方法。它可能看起来像这样:

public abstract class Animal
{
public abstract void Eat();
...
}
public class Giraffe : Animal
{
public override void Eat()
{
// Giraffe eating
}
...
}
public class Monkey : Animal
{
public override void Eat()
{
this.PeelBanana();
this.EatBanana(); //Or something like this
}
...
}

然后就去做

foreach(Animal a in animalList.Values){
a.Eat();
}

这是一种更加面向对象的解决方法。

关于c# - 从 C# 中的抽象列表调用对象特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20387332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com