您好,登錄后才能下訂單哦!
在C#中,由于其單繼承的特性,不能直接實現多繼承。但是可以通過如下幾種方式來模擬多繼承的功能:
interface IFlyable
{
void Fly();
}
interface ISwimmable
{
void Swim();
}
class Bird : IFlyable
{
public void Fly()
{
Console.WriteLine("Bird is flying");
}
}
class Fish : ISwimmable
{
public void Swim()
{
Console.WriteLine("Fish is swimming");
}
}
class Duck : IFlyable, ISwimmable
{
public void Fly()
{
Console.WriteLine("Duck is flying");
}
public void Swim()
{
Console.WriteLine("Duck is swimming");
}
}
class Flyable
{
public void Fly()
{
Console.WriteLine("Flying");
}
}
class Swimmable
{
public void Swim()
{
Console.WriteLine("Swimming");
}
}
class Duck
{
private Flyable _flyable = new Flyable();
private Swimmable _swimmable = new Swimmable();
public void Fly()
{
_flyable.Fly();
}
public void Swim()
{
_swimmable.Swim();
}
}
class Bird
{
public void Fly()
{
Console.WriteLine("Bird is flying");
}
}
class Fish
{
public void Swim()
{
Console.WriteLine("Fish is swimming");
}
}
class Duck
{
private Action _fly;
private Action _swim;
public Duck()
{
Bird bird = new Bird();
_fly = bird.Fly;
Fish fish = new Fish();
_swim = fish.Swim;
}
public void Fly()
{
_fly();
}
public void Swim()
{
_swim();
}
}
這些方式可以在C#中模擬多繼承的功能,根據具體的情況選擇合適的方式來實現多繼承。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。