Skip to content
欢迎扫码关注公众号

.NET Core 实战 [No.84] 显式实现接口

显示实现接口就是在实现接口的成员前面加上接口的名称。这种方法可以有效解决接口成员冲突问题。

类是可以继承多个接口的,当接口中有方法声明相同时,就需要显示的实现接口。

csharp
void IDownloader.Start()
{
}

调用时也需要转换成对应的接口类型才可以调用,使用实现类直接调用会报错。

示例代码

IDownloader.cs

csharp
interface IDownloader
{
    void Start();
}

IUploader.cs

csharp
interface IUploader
{
    void Start();
}

NetworkManager.cs

csharp
class NetworkManager : IDownloader, IUploader
{
    void IDownloader.Start()
    {
        Console.WriteLine("正在下载...");
    }

    void IUploader.Start()
    {
        Console.WriteLine("正在上传...");
    }
}

使用示例:

csharp
var manager = new NetworkManager();
(manager as IDownloader).Start(); // 正在下载...
(manager as IUploader).Start(); // 正在上传...
//manager.Start(); // 该语句报错:未包含 "Start" 的定义

参考:《.NET Core 实战:手把手教你掌握 380 个精彩案例》 -- 周家安 著


Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.