Interface Key Note

本文详细介绍了C#中接口的两种实现方式:隐式和显式,并通过实例解释了接口映射的用法。重点阐述了显式接口实现的必要性以及接口继承时如何正确映射接口成员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Interface Key Notes ( MSDN Interface)
1. Explicit Interface Implementation
There are 2: implicit and explicit interface implementation. Implicit type is normal to be used. Here, to understand more about why needs explicit interface implementation, give 2 reasons got from
Unleashed C#:
    -- Hide interface method / event / property / indexer in case to direct use the derived class.
    -- There are same signature functions in the derived class's parent interfaces, so it needs things like IBroker.GetRating and IAdviser.GetRating explicitly to get two implementations.

"Sometimes it’s necessary to explicitly declare which interface a class or struct member implements. One common reason for explicit implementation is when there is multiple interface inheritance and two or more interfaces declare a member with the same name.
Another reason to use explicit interface implementation is to hide a specific implementation.
To perform explicit interface implementation, a class implements an interface member by using its fully qualified name. The implementation is not declared with modifiers, because
they are implicitly hidden from an object of the implementing class. However, they are implicitly visible to objects of the explicit interface type."

2. Interface Mapping .
public class Accountant : StockBroker, IBroker
{
// no implementation
}
If StockBroker's implementation matchs IBroker's requirement, the Accountant class won't require any implementation to get compiler believe it's correct! This is interface mapping in C#!

This is because with C# interface mapping, the implementation of the StockBroker class is used to map to the implementation requirements of the IBroker interface.

3. Can Add Virtual in derived class of the interfaces

Normally, we don't need to add virtual keyword in the derived class of interfaces. But there are cases we need to add virtual to enable the derived class's children can override some behaviors. From MSDN: "It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members."

转载于:https://www.cnblogs.com/taoxu0903/archive/2010/05/11/1732583.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值