Sma*_*EGA 1 .net c# inheritance interface class
我们定义接口如下:
interface IMyInterface
{
void MethodToImplement();
}
Run Code Online (Sandbox Code Playgroud)
以及如下的恭维:
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Run Code Online (Sandbox Code Playgroud)
而不是创建一个接口,为什么我们可以直接使用该功能如下:-)
class InterfaceImplementer
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
您没有在底部示例中实现接口,您只是创建InterfaceImplementer的对象
编辑:在此示例中,不需要接口.但是,在尝试编写松散耦合的代码时,它们非常有用,您无需依赖具体对象.它们还用于定义契约,其中任何实现它们的东西也必须实现它定义的每个方法.
有很多信息,这里只是一个简短的介绍http://www.csharp-station.com/Tutorials/Lesson13.aspx
如果你真的想了解更多关于接口以及它们如何帮助编写好的代码,我会推荐Head First Design Patterns一书.亚马逊链接