zoukankan      html  css  js  c++  java
  • 【C#】C#接口转

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

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

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

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

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

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

      入门示例:

    using System;

    interface MyInterface
    {
      int Sqr(int x);
    }

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


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

        MyInterface intf = new MyClass();
        Console.WriteLine(intf.Sqr(3));

        Console.ReadKey();
      }
    }

      一个接口得到不同的实现:

    using System;

    interface MyInterface
    {
      int Method(int x, int y);
    }

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

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


    class Program
    {
      static void Main()
      {
        MyInterface intf1 = new MyClass1();
        MyInterface intf2 = new MyClass2();

        Console.WriteLine(intf1.Method(3, 2)); // 5
        Console.WriteLine(intf2.Method(3, 2)); // 1

        Console.ReadKey();
      }
    }

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

    using System;

    interface MyInterface1
    {
      void Method();
    }

    interface MyInterface2
    {
      void Method();
    }


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


    class Program
    {
      static void Main()
      {
        MyInterface1 intf1 = new MyClass();
        MyInterface2 intf2 = new MyClass();

        intf1.Method(); // MyInterface1_Method
        intf2.Method(); // MyInterface2_Method

        Console.ReadKey();
      }
    }

  • 相关阅读:
    C#多线程同步重新梳理
    word打不开,Microsoft Office Word 遇到问题需要关闭。。。总提示进入安全...
    SMTP协议
    【转载】Hadoop集群(第10期)_MySQL关系数据库 天高地厚
    备份与恢复的原理 . 天高地厚
    ubuntu server 使用parted分区 天高地厚
    Flex开发中遇到未整理资源 天高地厚
    Oracle RAC + Data Guard 环境搭建 . 天高地厚
    【转载】oracle事务之oracle读一致性 . 天高地厚
    理解PGA(2)pga_aggregate_target详解 . 天高地厚
  • 原文地址:https://www.cnblogs.com/cuishao1985/p/1510919.html
Copyright © 2011-2022 走看看