C#中的interface
接口(interface)
接口泛指實體把自己提供給外界的一種抽象化物(可以為另一實體),用以由內(nèi)部操作分離出外部溝通方法,使其能被修改內(nèi)部而不影響外界其他實體與其交互的方式。
?
接口實際上是一個約定:
如:IClonable, IComparable;
接口是抽象成員的集合:
ICloneable含有方法clone();
IComparable含有方法compare();
接口是一個引用類型,比抽象更抽象。
?
幫助實現(xiàn)多重繼承:
?
接口的用處:
1.實現(xiàn)不相關(guān)類的相同行為,不需要考慮這些類的層次關(guān)系;
2.通過接口可以了解對象的交互界面,而不需要了解對象所在的類。例如:public sealed class String: ICloneable, IComparable, IConvertible, IEnumerable.
?
定義一個接口:
?
public interface IStringList //接口一般用I作為首字母 {//接口聲明不包括數(shù)據(jù)成員,只能包含方法、屬性、事件、索引等成員//使用接口時不能聲明抽象成員(不能直接new實例化)void Add ( string s ) ; int Count{ get; } string this[int index] { get; set; } }//public abstract 默認,這兩個關(guān)鍵詞不寫出來?
?
實現(xiàn)接口:
?
class 類名 : [父類 , ] 接口, 接口, 接口, ..... 接口{public 方法 () { ...... }}?
?
顯示接口成員實現(xiàn):
在實現(xiàn)多個接口時,如果不同的接口有同名的方法,為了消除歧義,需要在方法名前寫接口名: void IWindow.Close(){......};
調(diào)用時,只能用接口調(diào)用: (( IWindow ) f ).Close();
?
接口示例:
using System;namespace TestInterface {interface Runner{void run();}interface Swimmer{void swim();}abstract class Animal //抽象類用作基類 {abstract public void eat();}class Person : Animal, Runner, Swimmer{public void run(){Console.WriteLine("run");}public void swim(){Console.WriteLine("swim");}public override void eat(){Console.WriteLine("eat");}public void speak(){Console.WriteLine("speak");}}class Program{ static void m1(Runner r){r.run();}static void m2(Swimmer s){s.swim();}static void m3(Animal a){a.eat();}static void m4(Person p){p.speak();}public static void Main(string [] args){Person p = new Person();m1(p);m2(p);m3(p);m4(p);Runner a = new Person();a.run();Console.ReadKey(true);}} }運行結(jié)果:
?
含有同名方法的多個接口繼承:
using System; class InterfaceExplicitImpl {static void Main(){FileViewer f = new FileViewer();f.Test();( (IWindow) f ).Close(); //強制轉(zhuǎn)換,消除同名歧義 IWindow w = new FileViewer();w.Close();Console.ReadKey(true);} }interface IWindow {void Close(); } interface IFileHandler {void Close(); } class FileViewer : IWindow, IFileHandler {void IWindow.Close (){Console.WriteLine( "Window Closed" );}void IFileHandler.Close(){Console.WriteLine( "File Closed" );}public void Test(){( (IWindow) this ).Close(); //不同接口含有同名方法,需要在方法前面寫接口名 } }?
轉(zhuǎn)載于:https://www.cnblogs.com/bincoding/p/4869804.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的C#中的interface的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装DNN时,数据库连接字符串的设置
- 下一篇: 中毒,重装,杀毒……最近一段时间,很烦的