简体   繁体   English

接口:声明具有继承接口的类

[英]Interface: Declaring a class with inherited interface

I'm not sure what this is call or how to google for an explanation but here goes 我不确定这是什么电话或如何谷歌解释,但这里

let said I have a interface call IView and a class inherited IView call View class. 我说我有一个接口调用IView和一个继承IView的类调用View类。 In some projects I see the below code: 在某些项目中,我看到以下代码:

IView view = new View();

Why do that? 为什么这样? Why not just do 为什么不这样做呢

var view = new View();

Is there a purpose for declaring a interface then create a View object? 是否有用于声明接口然后创建View对象的目的? why not do the second step? 为什么不做第二步呢?

If you use the var keyword, the type of the variable will be automatically detected and will probably be of the type View instead of IView . 如果使用var关键字,将自动检测变量的类型,并且可能是View类型而不是IView It's more clear to the reader of your code that you actually meant to have an IView reference. 对于您的代码的读者来说,您实际上想要有一个IView引用更清楚。

The idea of interfaces, is that it doesn't matter which class implements them, so your code is built upon the knowledge that this .. thing.. implements all IView's properties and methods, disregarding which class it is. 接口的概念是,哪个类实现它们并不重要,所以你的代码建立在知道这个..的东西..实现所有IView的属性和方法,忽略它是哪个类。

A setup like this will allow you to easily insert different classes later. 这样的设置将允许您稍后轻松插入不同的类。 You could substitute this line for a call to an IView factory of which you don't know at all which class instance it returns. 您可以将此行替换为对IView 工厂的调用,您不知道它返回哪个类实例。

您可能需要查看除了View之外的其他内容,例如,如果View是一个SpecialView类,那么var view将不允许您稍后为其分配GenericView,即使它们都具有IView接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM