C# 接口(接口可以继承接口)

接口可以继承接口

之前我们已经知道接口实现可以从基类被继承,而接口本身也可以从一个或多个接口继承而来。

  • 要指定某个接口继承其他的接口,应在接口声明中把基接口名称以逗号分隔的列表形式

    放在接口名称后面的冒号之后,如下所示。

  • 类在基类列表中只能有一个类名,而接口可以在基接口列表中有任意多个接口。

    • 列表中的接口本身可以继承其他接口。
    • 结果接口包含它声明的所有成员和基接口的所有成员。
      图16-11中的代码演示了3个接口的声明。IDataIO接口从前两个接口继承而来图右边部分
      显示IDataIO包含了另外两个接口。
csharp 复制代码
interface IDataIO:IDataRetrieve,IDatatStore
{
    interface IDataRetrieve
    {
        int GetData();
    }

    interface IDatatStore
    {
        void SetData(int x);
    }
    //从前两个接口继承而来
    interface IDataIO:IDataRetrieve,IDatatStore
    {

    }

    class MyData:IDataIO{
        int nPrivateData;
        public int GetData()
        {
            return nPrivateData;
        }

        public void SetData(int x)
        {
            nPrivateData=x;
        }
    }

    class Program{
        static void Main(){
            MyData data=new MyData();
            data.SetData(5);
            Console.WriteLine("{0}",data.GetData());
        }
    }
}

不同类实现一个接囗的示例

如下代码演示了已经介绍过的接口的一些方面。程序声明一个名为Animal的类,它被作为

其他一些表示各种类型动物的类的基类。它还声明了一个叫作ILiveBirth的接口。

Cat、Dog和Bird类都从Animal基类继承而来。Cat和Dog都实现了ILiveBirth接口,而Bird

类没有。

在Main中,程序创建了Animal对象的数组并用3个动物类的对象进行填充。然后,程序遍

历数组并使用as运算符获取指向ILiveBirth接口的引用,并调用了BabyCalled方法。

csharp 复制代码
interface ILiveBirth   //声明接口
{
    string BabyCalled();
}

class Animal{}   //基类Animal

class Cat:Animal,ILiveBirth    //声明Cat类
{
    string ILiveBirth.BabyCalled()
    {return "kitten";}
}

class Dog:Animal,ILiveBirth    //声明Dog类
{
    string ILiveBirth.BabyCalled()
    {
        return "puppy";
    }

    class Bird:Animal          //声明Bird类
    {

    }

    class Program
    {
        static void Main()
        {
            Animal[] animalArray=new Animal[3];   //创建Animal数组
            animalArray[0]=new Cat();             //插入Cat类对象
            animalArray[1]=new Bird();            //插入Bird类对象
            animalArray[2]=new Dog();             //插入Dog类对象
            foreach(Animal a in animalArray)      //在数组中循环
            {
                ILiveBirth b= a as ILiveBirth;    //如果实现ILiveBirth
                if(b!=null)
                    Console.WriteLine($"Baby is called:{b.BabyCalled()}");
            }
        }
    }
}

图16-12演示了内存中的数组和对象。

相关推荐
zzb158032 分钟前
RAG from Scratch-优化-query
java·数据库·人工智能·后端·spring·mybatis
wuqingshun3141591 小时前
如何停止一个正在退出的线程
java·开发语言·jvm
卷福同学1 小时前
QClaw内测体验,能用微信指挥AI干活了
人工智能·算法·ai编程
sali-tec1 小时前
C# 基于OpenCv的视觉工作流-章34-投影向量
图像处理·人工智能·opencv·算法·计算机视觉
xiaoye-duck1 小时前
《算法题讲解指南:递归,搜索与回溯算法--递归》--3.反转链表,4.两两交换链表中的节点,5.快速幂
数据结构·c++·算法·递归
Eward-an1 小时前
【算法竞赛/大厂面试】盛最多水容器的最大面积解析
python·算法·leetcode·面试·职场和发展
山栀shanzhi1 小时前
归并排序(Merge Sort)原理与实现
数据结构·c++·算法·排序算法
阿豪学编程1 小时前
LeetCode438: 字符串中所有字母异位词
算法·leetcode
Trouvaille ~1 小时前
【递归、搜索与回溯】专题(七):FloodFill 算法——勇往直前的洪水灌溉
c++·算法·leetcode·青少年编程·面试·蓝桥杯·递归搜索回溯
地平线开发者2 小时前
征程 6P codec decoder sample
算法·自动驾驶