您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。