C#中的interface

接口(interface

接口泛指实体把自己提供给外界的一种抽象化物(可以为另一实体),用以由内部操作分离出外部沟通方法,使其能被修改内部而不影响外界其他实体与其交互的方式。

 

接口实际上是一个约定:

如:IClonable, IComparable;

接口是抽象成员的集合:

ICloneable含有方法clone();

IComparable含有方法compare();

接口是一个引用类型,比抽象更抽象。

 

帮助实现多重继承:

 

接口的用处:

1.实现不相关类的相同行为,不需要考虑这些类的层次关系;

2.通过接口可以了解对象的交互界面,而不需要了解对象所在的类。例如:public sealed class String: ICloneable, IComparable, IConvertible, IEnumerable.

 

定义一个接口:

 

public interface IStringList //接口一般用I作为首字母

{
    //接口声明不包括数据成员,只能包含方法、属性、事件、索引等成员
    //使用接口时不能声明抽象成员(不能直接new实例化)

    void Add ( string s ) ;  

    int Count{ get; } 

    string this[int index] { get; set; } 

}

//public abstract 默认,这两个关键词不写出来

 

实现接口:

 

class 类名 : [父类 , ] 接口, 接口, 接口, ..... 接口

{

public 方法 () { ...... }

}

 

显示接口成员实现:

在实现多个接口时,如果不同的接口有同名的方法,为了消除歧义,需要在方法名前写接口名: void IWindow.Close(){......};

调用时,只能用接口调用: (( IWindow ) f ).Close();

接口示例:

using System;

namespace TestInterface
{
    interface Runner
    {
        void run();
    }
    interface Swimmer
    {
        void swim();
    }
    abstract class Animal  //抽象类用作基类
    {
        abstract public void eat();
    }
    class Person : Animal, Runner, Swimmer
    {
        public void run()
        {
            Console.WriteLine("run");
        }
        public void swim()
        {
            Console.WriteLine("swim");
        }
        public override void eat()
        {
            Console.WriteLine("eat");
        }
        public void speak()
        {
            Console.WriteLine("speak");
        }
    }
    class Program
    {        
        static void m1(Runner r)
        {
            r.run();
        }
        static void m2(Swimmer s)
        {
            s.swim();
        }
        static void m3(Animal a)
        {
            a.eat();
        }
        static void m4(Person p)
        {
            p.speak();
        }
        
        public static void Main(string [] args)
        {
            Person p = new Person();
            m1(p);
            m2(p);
            m3(p);
            m4(p);
            Runner a = new Person();
            a.run();
            
            Console.ReadKey(true);
        }
    }
}

运行结果:

含有同名方法的多个接口继承:

using System;
class InterfaceExplicitImpl
{
    static void Main()
    {
        FileViewer f = new FileViewer();
        f.Test();
        ( (IWindow) f ).Close();  //强制转换,消除同名歧义
          
        IWindow w = new FileViewer();
        w.Close();
        
        Console.ReadKey(true);
    }
}
  
interface IWindow
{
    void Close();
}
interface IFileHandler
{
    void Close();
}
class FileViewer : IWindow, IFileHandler
{
    void IWindow.Close ()
    {
        Console.WriteLine( "Window Closed" );
    }
    void IFileHandler.Close()
    {
        Console.WriteLine( "File Closed" );
    }
    public void Test()
    {
        ( (IWindow) this ).Close(); //不同接口含有同名方法,需要在方法前面写接口名
    }
}
原文地址:https://www.cnblogs.com/bincoding/p/4869804.html