接口定义了所有类继承接口时应遵循的语法合同。
接口定义了语法合同 “是什么” 部分,派生类定义了语法合同 “怎么做” 部分。
接口只包含了成员的声明。成员的定义是派生类的责任。
接口声明可以包含以下成员的声明(没有任何实现的签名):
方法属性索引器事件示例: 下例演示了接口实现。 在此示例中,接口包含属性声明,类包含实现。 实现 IPoint 的类的任何实例都具有整数属性 x 和 y。
namespace interfaceDemo { interface IPoint { // Property signatures: int X { get; set; } int Y { get; set; } // method signatures: double Distance { get; } void print(); } class Point : IPoint { // Constructor: public Point(int x, int y) { X = x; Y = y; } // Property implementation: public int X { get; set; } public int Y { get; set; } // Property implementation public double Distance { get { return Math.Sqrt(X * X + Y * Y); } set { } } // Method implementation. void IPoint.print() { Console.WriteLine("This is a Point!"); } } class Program { static void PrintPoint(IPoint p) { Console.WriteLine("x={0}, y={1},dis ={2}", p.X, p.Y,p.Distance); } static void Main(string[] args) { IPoint p = new Point(4, 3); Console.Write("My Point: "); PrintPoint(p); p.print(); Console.ReadLine(); } } }以上的示例中,显示定义了接口IPoint,包含了属性和方法的成员;Point继承了该接口,而且实现了接口的成员,最后在main函数创建Point实例.