gpt4 book ai didi

c# - 为什么要显式接口(interface)实现?

转载 作者:太空狗 更新时间:2023-10-29 17:44:12 25 4
gpt4 key购买 nike

我最近实现了一个类:

class TestClass : IDisposable
{
RegistryKey m_key;
public TestClass()
{
m_key = Registry.CurrentUser.OpenSubKey("Software", false);
}

public void Dispose()
{
// m_key.Dispose();
IDisposable disp = m_key;
disp.Dispose();
}
}

如果我取消注释对 Dispose 的直接调用,我会收到错误 CS0117(“'Microsoft.Win32.RegistryKey' 不包含 'Dispose' 的定义”)。一些谷歌搜索把我带到了this thread ,在那里我了解到发生了什么,所以我现在了解它的机制。 MSDN文档表明作者更喜欢我调用 Close() 而不是 Dispose(),但没有解释原因。

这种模式的目的是什么(我想我也在 IO 类中看到过)?鉴于这是类作者的故意决定,上面的代码(通过 IDisposable 接口(interface)调用 Dispose)有多糟糕?这不会太糟糕 - 毕竟,这是在 using 语句中会发生的事情,对吧?

[编辑:1) 将标题从“非公开”更改为“显式” 2) 从我的代码中删除了显式实现,不小心从实验中遗漏了]

最佳答案

这称为显式接口(interface)实现。在您的示例中,由于您将 Dispose() 方法定义为“void IDisposable.Dispose()”,因此您也显式实现了 IDisposable 接口(interface)。

这通常是为了避免碰撞。如果 Microsoft 曾经想添加另一个 Dispose() 方法来对 RegistryKey 执行其他操作,除非他们使用该接口(interface)的显式实现,否则他们将无法做到。

这通常使用通用的 IEnumerable 接口(interface)来完成。它还要求您实现非通用接口(interface) IEnumerable。这两个接口(interface)中唯一的成员是GetEnumerator,泛型的更好用,所以通常这样实现:

public clas SomeClass : IEnumerable<SomeOtherClass>
{
public IEnumerator<SomeOtherClass> GetEnumerator ()
{
...
}

IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}

这样当您调用 SomeClass 的 GetEnumator 方法的对象时,它会调用泛型版本,因为另一个是显式实现的,允许我们获得强类型泛型。

请参阅 Jesse Liberty 的 Programming C# 第 166-169 页(我有第四版)。

关于c# - 为什么要显式接口(interface)实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/408415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com