C# 语言参考

 

  接口(C# 参考)

 

  定义:接口是一种约束形式,其中只包括成员定义,不包含成员实现的内容。

 

  目的:接口的主要目的是为不相关的类提供通用的处理服务,由于C#中只允许树形结构中的单继承,即一个类只能继承一个父类,所以接口是让一个类具有两个以上基类的唯一方式。

 

  接口只包含方法委托事件的签名。方法的实现是在实现接口的类中完成的,如下面的示例所示:

 
 

  interface ISampleInterface

 

  {

 

  void SampleMethod();

 

  }

 

  class ImplementationClass : ISampleInterface

 

  { //实现接口成员。

 

  void ISampleInterface.SampleMethod()

 

  { //方法实现。

 

  static void Main()

 

  { // 定义一个接口的实例变量 obj。

 

  ISampleInterface obj = new ImplementationClass();

 

  //调用(obj)的成员方法。

 

  obj.SampleMethod();

 

  }

 

  }

 

  }

 

  备注

 

  接口可以是命名空间或类的成员,并且可以包含下列成员的签名:

 

  方法属性索引器事件一个接口可从一个或多个基接口继承。

 

  当基类型列表包含基类和接口时,基类必须是列表中的第一项。

 

  实现接口的类可以显式实现该接口的成员。显式实现的成员不能通过类实例访问,而只能通过接口实例访问,例如:

 

  有关显式接口实现的更多详细信息和代码示例,请参见显式接口实现(C# 编程指南)。

 

  示例

 

  下面的示例演示了接口实现。在此例中,接口 IPoint 包含属性声明,后者负责设置和获取字段的值。Point 类包含属性实现。

 

  复制

 

  // keyword_interface_2.cs

 

  // Interface implementation

 

  using System;

 

  interface IPoint

 

  {

 

  // Property signatures:

 

  int x{get; set;}

 

  int y{get; set;}

 

  }

 

  class Point : IPoint

 

  {

 

  // Fields:

 

  private int _x;

 

  private int _y;

 

  // Constructor:

 

  public Point(int x, int y)

 

  {

 

  _x = x;

 

  _y = y;

 

  }

 

  // Property implementation:

 

  public int x

 

  {

 

  get { return _x; }

 

  set { _x = value; }

 

  }

 

  public int y

 

  {

 

  get { return _y; }

 

  set { _y = value; }

 

  }

 

  }

 

  class MainClass

 

  {

 

  static void PrintPoint(IPoint p)

 

  {

 

  Console.WriteLine("x={0}, y={1}", p.x, p.y);

 

  }

 

  static void Main()

 

  {

 

  Point p = new Point(2, 3);

 

  Console.Write("My Point: ");

 

  PrintPoint(p);

 

  }

 

  输出My Point: x=2, y=3

 posted on 2011-06-14 19:30  编程小兵  阅读(189)  评论(0编辑  收藏  举报