Home >Backend Development >C++ >Implicit vs. Explicit Interface Implementation in C#: When Should I Use Which?
C# interface implementation: hidden and explicit method
The interface in C# defines the contract that the class or the structure must follow. When implementing the interface, you can choose two methods: hidden implementation and explicit implementation.
hidden implementation
Rectify the interface method as part of a class or structure. These methods can be accessed in two ways: class and interface. Examples as follows:
Expressing
<code class="language-csharp">public interface ICopyable { void CopyTo(Array array, int index); } public class MyClass : ICopyable { public void CopyTo(Array array, int index) { // 实现代码 } }</code>Expressing the interface method separately in the class or structure. These methods can only be accessed through interfaces and cannot be accessed through class. Examples as follows:
When to use hidden or explicit implementation
<code class="language-csharp">public interface ICopyable { void CopyTo(Array array, int index); } public class MyClass : ICopyable { void ICopyable.CopyTo(Array array, int index) { // 实现代码 } }</code>When the implementation of a class or structure is completely consistent with the definition in the interface,
hidden implementation . It simplifies the code by eliminating the needs of the definition of explicit method.
Expressing :
You need to realize multiple interfaces with the same method name but implement different. It needs to be implemented from a hidden interface from a public API of a class or structure.
Advantages: Allows more detailed control to implement details, and help avoids ambiguousness when defining conflict methods in multiple interfaces.
Disadvantages:The code may lead to lengthy and complicated.
Into the implementation:Microsoft's guidance principles on explicit implementation
Microsoft's guidance principles are usually recommended to avoid explicit implementation because it may lead to accidental behavior. However, the principle of this guidance may be previously formulated before dependency injection (DI). When using DI, interfaces are usually passed. In this case, it may be more beneficial to explicit implementation.The above is the detailed content of Implicit vs. Explicit Interface Implementation in C#: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!