黑马程序员技术交流社区

标题: 有关接口 [打印本页]

作者: 右哼哼    时间: 2014-1-8 16:03
标题: 有关接口
本帖最后由 右哼哼 于 2014-1-9 16:58 编辑

什么是接口,接口有什么用处??为什么要用接口??、
作者: lwx    时间: 2014-1-8 16:08
接口是为了规范行为,它没有实现,也不能实例化,一个类如果实现了接口,那么这个类要满足接口中的所有约定
普通类是可以有实现的,也可以实例化或置为static,一个类如果继承了另一个类,那么可以默认使用父类中的实现

在你熟练运用面向对象的情况下,接口可以更好地解除类之间的耦合,使程序更简单更易维护
作者: 一席倾城    时间: 2014-1-8 16:38
接口只包含方法、属性、事件或索引器的签名。成员的实现是在实现接口的类或结构中完成的,如下面的示例所示:
interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation:
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

接口可以是命名空间或类的成员,并且可以包含下列成员的签名:
方法
属性
索引器
事件
一个接口可从一个或多个基接口继承。
当基类型列表包含基类和接口时,基类必须是列表中的第一项。
实现接口的类可以显式实现该接口的成员。显式实现的成员不能通过类实例访问,而只能通过接口实例访问。
下面的示例演示了接口实现。在此示例中,接口包含属性声明,类包含实现。
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);
   }
}
// Output: My Point: x=2, y=3




然后然后接口的好处在于:
一,代码规范化,不会出现一样的功能有几种命名,还有就是间接地实现了多继承
二,保证了代码的封装性,另外接口是可以多重继承的
三,接口是对业务逻辑的抽象,类是业务规则的一种实现,是具体化。一个类可以实现多种业务规则,也就是多个接口。将接口和类分离,是为了适应业务的变化
其实主要就是便于重用




还有,妹子,以后要不要注意提的问题,不要只为了技术分提问哈




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2