C#创建接口和定义抽象类(二)

多个接口使用

之前我们说到在C#接口其实是模拟多重接口,那我们如何让一个类就是继承多接口呢,在此前我们已经创建了一个叫ILandBound(陆地动物)的接口,那么我们可以再创建一个IMarineorganism(海底生物)的接口,我们想想海龟是不是可以上岸又可以在海里,如果使用继承的话只继承 ILandBound(陆地动物)但它还有海底生物的第一面不够完整,继承IMarineorganism(海底生物)也是一样,所以接口的作用就产生了,我们可以实现海龟既有陆地动物的特性也有海底生物的特性。

代码实现

首先我们创建一个新的接口叫IMarineorganism,添加方法为活动方式

namespace CsharpInterface
{
    interface IMarineorganism
    {
        void Activity();//在海底活动的方式
    }
}

然后我们创建一个海龟并继承这两个接口,并实现接口方法

namespace CsharpInterface
{
    class SeaTurtle : ILandBound, IMarineorganism
    {
        //IMarineorganism的方法
        //海龟在海里的活动是游泳
        public void Activity()
        {
            Console.WriteLine("我在游泳");
        }
        //ILandBound的方法
        //海龟有多少条腿
        public int NumberOfLegs()
        {
            return 4;
        }
    }
}

最后在主入口中实现代码并进行调试

namespace CsharpInterface
{
    class Program
    {
        static void Main(string[] args)
        {
            SeaTurtle turtle = new SeaTurtle();
            ILandBound land = turtle;
            IMarineorganism sea = new SeaTurtle();     
            sea.Activity();
            Console.WriteLine("海龟有"+land.NumberOfLegs()+"条腿");
        }
    }
}

到这里其实会有一个疑问,如果你这样写的话也是可以实现的,就是我们完全可以不通过接口引用类再调用方法也可以调用方法

namespace CsharpInterface
{
    class Program
    {
        static void Main(string[] args)
        {
            SeaTurtle turtle = new SeaTurtle();
            ILandBound land = turtle;
            IMarineorganism sea = new SeaTurtle();
            turtle.Activity();
        }
    }
}

为什么我们要这么多此一举绕一个大圈来实现方法,其实一个类并不能代表什么,如果我们要实现一千,一万种动物,我们每个动物都自己去写上方法是不是很麻烦,而且没种动物都自己写上去方法就很麻烦了,我们个人做练习学习时候可能感觉没那么强,但是如果我们接触到团队项目就知道了,团队都是要有一定约束的方法,不然大家自己写自己都不知道各自都不知道对方在写什么。

发布了15 篇原创文章 · 获赞 7 · 访问量 1926

猜你喜欢

转载自blog.csdn.net/weixin_40875853/article/details/92630188