C Sharp(十)
發佈於 2018-11-10
这一篇,我们再回来说说最后一种类型: 接口(interface)。
接口是指定一组函数成员而不实现他们的引用类型。
interface IInfo { string GetName(); string GetAge(); } |
---|
我们可以用类或结构来实现接口。
class MyCls: IComparable { public int TheValue; public int CompareTo(object obj) { MyCls cls = (MyCls)obj; if (TheValue > cls.TheValue) return 1; if (TheValue < cls.TheValue) return -1; return 0; } } |
---|
public interface IMyInterface { //注意: 接口函数成员不能有访问修饰符 int DoStuff(int val); } |
---|
要实现接口:
注意: 如果有继承,并实现接口,基类名必须出现在接口之前:
class Derived : BaseClass, IIfc1, IIfc2 { //... } |
---|
与类的继承不同,接口可以多继承。
interface IData : IDataR, IDataS { //... } |
---|