What is the advantage of using Interface?

2019-05-10 01:55发布

What is the use of using Interface?

I heard that it is used instead of multiple inheritance and data-hiding can also be done with it.

Is there any other advantage, where are the places interface is used, and how can a programmer identify that interface is needed?

What is the difference between explicit interface implementation and implicit interface implementation?

标签: c# .net oop
7条回答
我想做一个坏孩纸
2楼-- · 2019-05-10 02:25

An interface simply separates the description of a class API from its implementation. It's about separation of concerns which is fundamental to any robust software project. You can replace the implementing classes without breaking any other code.

One area where this is particularly helpful is with unit testing, as it allows you to mock out the interfaces that you don't want to test as part of a given test case.

Having entirely unrelated classes implement the same interface also allows you to write methods that can operate on different classes in different hierarchies (i.e. no common ancestor other than object), without them having to take object as their type. For example you can write a method that takes IEnumerable, and pass it List, Array etc. Without interfaces or a common base type this wouldn't be possible (except by casting from object).

查看更多
登录 后发表回答