接口可以繼承接口
之前我們已經知道接口實現可以從基類被繼承,而接口本身也可以從一個或多個接口繼承而來。
-
要指定某個接口繼承其他的接口,應在接口聲明中把基接口名稱以逗號分隔的列表形式
放在接口名稱后面的冒號之后,如下所示。 -
類在基類列表中只能有一個類名,而接口可以在基接口列表中有任意多個接口。
- 列表中的接口本身可以繼承其他接口。
- 結果接口包含它聲明的所有成員和基接口的所有成員。
圖16-11中的代碼演示了3個接口的聲明。IDataIO接口從前兩個接口繼承而來圖右邊部分
顯示IDataIO包含了另外兩個接口。
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方法。
interface ILiveBirth //聲明接口
{string BabyCalled();
}class Animal{} //基類Animalclass 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; //如果實現ILiveBirthif(b!=null)Console.WriteLine($"Baby is called:{b.BabyCalled()}");}}}
}
圖16-12演示了內存中的數組和對象。