[C#] 接口

接口只含有 method, events 和 properties 的声明
接口可以隐式或显式实现
接口不能包含私有成员,所有成员默认情况下都为public

下面的两个类的方法,一个将log输出到控制台,一个将log写到文件:

interface ILog
{
    void Log(string msgToLog);
}
class ConsoleLog : ILog
{
    public void Log(string msgToPrint)
    {
        Console.WriteLine(msgToPrint);
    }
}

class FileLog : ILog
{
    public void Log(string msgToPrint)
    {
        File.AppendText(@"C:\Log.txt").Write(msgToPrint);
    }
}

接口的概念和Java很像,然后显式声明是下面这样的,使用显式声明是因为,为了避免混淆,例如一个类实现了好多接口,或者每个接口中都有同名的方法,类似这样。

class ConsoleLog: ILog
{
    public void ILog.Log(string msgToPrint) // explicit implementation
    {
        Console.WriteLine(msgToPrint);
    }
}

然后可以实例化:

ILog log = new ConsoleLog();
//Or 
ILog log = new FileLog();

奇怪上面为什么不写成 ConsoleLog log = new ConsoleLog(); 或者 FileLog log = new FileLog();


[1] www.tutorialsteacher.com

猜你喜欢

转载自blog.csdn.net/ftell/article/details/81705844