rs232c接口:C# 语法练习(15): 接口

  接口只声明、无实现、不能例子化;

  接口可包含思路方法、属性、事件、索引器, 但无字段;

  接口成员都是隐式 public, 不要使用访问修饰符;

  类、结构和接口都可以继承多个接口;

  继承接口类必须实现接口成员, 除非是抽象类;

  类实现接口成员须是公共、非静态.

  入门举例:

using ;

erface MyInterface
{
   Sqr( x);
}

MyClass : MyInterface
{
  public Sqr( x) { x * x; }
}


Program
{
   void Main
  {
    MyClass obj = MyClass;
    Console.WriteLine(obj.Sqr(3)); // 9

    MyInterface f = MyClass;
    Console.WriteLine(f.Sqr(3));

    Console.ReadKey;
  }
}


  个接口得到区别实现:

using ;

erface MyInterface
{
   Method( x, y);
}

MyClass1 : MyInterface
{
  public Method( x, y) { x + y; }
}

MyClass2 : MyInterface
{
  public Method( x, y) { x - y; }
}


Program
{
   void Main
  {
    MyInterface f1 = MyClass1;
    MyInterface f2 = MyClass2;

    Console.WriteLine(f1.Method(3, 2)); // 5
    Console.WriteLine(f2.Method(3, 2)); // 1

    Console.ReadKey;
  }
}


  显示实现接口(接口名.思路方法):

using ;

erface MyInterface1
{
  void Method;
}

erface MyInterface2
{
  void Method;
}


MyClass : MyInterface1, MyInterface2
{
  /* 显示实现接口不需要访问修饰符; 但显示实现思路方法只能通过接口访问 */
  void MyInterface1.Method { Console.WriteLine("MyInterface1_Method"); }
  void MyInterface2.Method { Console.WriteLine("MyInterface2_Method"); }
}


Program
{
   void Main
  {
    MyInterface1 f1 = MyClass;
    MyInterface2 f2 = MyClass;

    f1.Method; // MyInterface1_Method
    f2.Method; // MyInterface2_Method

    Console.ReadKey;
  }
}


Tags:  c语言与matlab接口 c语言接口与实现 什么是c接口 rs232c接口

延伸阅读

最新评论

发表评论