C#中的interface
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C#中的interface
接⼝(interface)
接⼝泛指实体把⾃⼰提供给外界的⼀种抽象化物(可以为另⼀实体),⽤以由内部操作分离出外部沟通⽅法,使其能被修改内部⽽不影响外界其他实体与其交互的⽅式。
接⼝实际上是⼀个约定:
如:IClonable, IComparable;
接⼝是抽象成员的集合:
ICloneable含有⽅法clone();
IComparable含有⽅法compare();
接⼝是⼀个引⽤类型,⽐抽象更抽象。
帮助实现多重继承:
接⼝的⽤处:
1.实现不相关类的相同⾏为,不需要考虑这些类的层次关系;
2.通过接⼝可以了解对象的交互界⾯,⽽不需要了解对象所在的类。
例如:public sealed class String: ICloneable, IComparable, IConvertible, IEnumerable.
定义⼀个接⼝:
public interface IStringList //接⼝⼀般⽤I作为⾸字母
{
//接⼝声明不包括数据成员,只能包含⽅法、属性、事件、索引等成员
//使⽤接⼝时不能声明抽象成员(不能直接new实例化)
void Add ( string s ) ;
int Count{ get; }
string this[int index] { get; set; }
}
//public abstract 默认,这两个关键词不写出来
实现接⼝:
class类名 : [⽗类 , ] 接⼝, 接⼝, 接⼝, ..... 接⼝
{
public⽅法 () { ...... }
}
显⽰接⼝成员实现:
在实现多个接⼝时,如果不同的接⼝有同名的⽅法,为了消除歧义,需要在⽅法名前写接⼝名: void IWindow.Close(){......};调⽤时,只能⽤接⼝调⽤: (( 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);
}
}
}
运⾏结果:
含有同名⽅法的多个接⼝继承:
using System;
class InterfaceExplicitImpl
{
static void Main()
{
FileViewer f = new FileViewer();
f.Test();
( (IWindow) f ).Close(); //强制转换,消除同名歧义
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(); //不同接⼝含有同名⽅法,需要在⽅法前⾯写接⼝名 }
}。