您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。