在C#中,由于语言本身不支持多继承,但可以通过接口、委托、混合类等方式来模拟多继承的效果。
interface IFly
{
void Fly();
}
interface ISwim
{
void Swim();
}
class Bird : IFly
{
public void Fly()
{
Console.WriteLine("Bird can fly");
}
}
class Fish : ISwim
{
public void Swim()
{
Console.WriteLine("Fish can swim");
}
}
class Duck : IFly, ISwim
{
public void Fly()
{
Console.WriteLine("Duck can fly");
}
public void Swim()
{
Console.WriteLine("Duck can swim");
}
}
class Fly
{
public void FlyAction()
{
Console.WriteLine("Can fly");
}
}
class Swim
{
public void SwimAction()
{
Console.WriteLine("Can swim");
}
}
class Duck
{
private Fly fly = new Fly();
private Swim swim = new Swim();
public void Fly()
{
fly.FlyAction();
}
public void Swim()
{
swim.SwimAction();
}
}
class Fly
{
public void FlyAction()
{
Console.WriteLine("Can fly");
}
}
class Swim
{
public void SwimAction()
{
Console.WriteLine("Can swim");
}
}
class Duck
{
private Fly fly = new Fly();
private Swim swim = new Swim();
public void Fly()
{
fly.FlyAction();
}
public void Swim()
{
swim.SwimAction();
}
}
通过以上方式,可以在C#中模拟多继承的效果,实现类的复用和功能的扩展。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。