问题
There are two type of statements on internet about Interface
, that is
Statement A
Interfaces do not come in inheriting chain.
other statement B
Interfaces can inherit other interfaces
These two are contradicting statements.
Please tell me which one is right?
回答1:
They are both true, sort of.
Statement A: Interfaces don't strictly inherit. If you have a class that implements an interface, and you say
base.
You won't see members of the interface.
Statement B: This would read better as "Interfaces can implement other interfaces". You can have an implementation chain; but they're not really inheriting.
回答2:
Interfaces can inherit other interfaces, try it and you'll see that it works.
回答3:
Both statements are correct.
The second statement is correct. InterfaceA: InterfaceB is perfectly fine and classes implementing InterfaceA must also inherit InterfaceB.
What is meant by "Interfaces do not come in inheriting chain" means that if DerivedClass : BaseClass, InterfaceA, you can access BaseClass members from DerivedClass by using base.BaseClassMethod, while you cannot call base.InterfaceAMethod in the same way because interfaces are not part of the inheritance chain. Rather, their members are accessible via polymorphism.
回答4:
They are both true, because they are both possible with C#. BUT, as we write clean code and program to an interface instead of an implementation:
- We don't want to get surprised with the interface-chains.
- And, we follow the Interface segregation principle.
Consider this,
interface IFileRepository : IDisposable { ... }
This says, whomever implements the IFileRepository
, MUST implement the IDisposable
. But, I can write a FileRepository, which might not need to dispose any resource. Or another example during unit-testing that I write a FileRepository
-Stub for a class which uses it as dependency, but doesn't invoke Dispose()
at all, at least in the method I test. And yet, I have to implement IDisposable
.
Clean-design should not dictate such implementation. Concrete implementations should know what to provide.
class FileRespository : IFileRepository , IDisposable { ... }
回答5:
In the .NET world, interfaces can absolutely inherit other interfaces. Any implementing class is then expected to implement all methods and properties of all the interfaces it inherits.
If there is a naming contradiction, the implementing class has to use explicit interface implementations.
来源:https://stackoverflow.com/questions/10350543/is-interface-comes-in-inheritance-chain-or-not