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. 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? 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
. It's more clear to the reader of your code that you actually meant to have an IView
reference.
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.
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.
您可能需要查看除了View之外的其他内容,例如,如果View是一个SpecialView类,那么var view
将不允许您稍后为其分配GenericView,即使它们都具有IView接口。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.