interfaces
直接进入我们精彩的内容
==接口与抽象类类似,都无法申明变量
它们的区别与相似之处:
Abstract Class Vs. Interface
ØInterfaces are very similar to abstract classes.
ØC# doesn’t allow multiple inheritance with classes.
ØC# does allow to implement any number of interfaces and derive from one base class.
一个类可以有多个接口,但是必须实现接口里的所有函数
来举个例子:
namespace ConsoleApplication1
{
class Program
{
public interface IStorable
{
void Read();
void Write();
}
interface ICompressible
{
void Compress();
void Decompress();
}
interface ILoggedCompressible : ICompressible
{
void LogSavedBytes();
}
public class Document : IStorable, ICompressible
{
public void Read()
{
Console.WriteLine("read");
}
public void Write()
{
Console.WriteLine("write");
}
public void Compress()
{ }
public void Decompress()
{ }
}
static void Main(string[] args)
{
Document document = new Document();
document.Write();
}
}
}
//类里的函数必须public
接下来介绍显式与隐式接口里函数的定义
增加了一个新的接口:
interface ITalk
{
void Talk();
void Read();
}
实现显式定义:
void ITalk.Read()
{
Console.WriteLine("reeeead");
}
//这里不加public
隐式加virtual
static void Main(string[] args)
{
Document firstDocument = new Document();
firstDocument.Read();
ITalk secondDocument = firstDocument;
secondDocument.Read();
}

显示定义的接口方法,不能有abstract, virtual, override, or new 修饰符。
因为显示实现的接口成员不能继承。
最后我感觉接口的使用要比抽象类方便很多。