【问题标题】:Why Dictionary<T, V> explicitly implements ICollection<KeyValuePair<T, V>> when it is already inherited by IDictionary<T,V>为什么 Dictionary<T, V> 已被 IDictionary<T,V> 继承时显式实现 ICollection<KeyValuePair<T, V>>
【发布时间】:2014-01-23 22:02:19
【问题描述】:

最近有朋友问我,为什么Dictionary&lt;T, V&gt; 已经被IDictionary&lt;T,V&gt; 继承了,却要显式实现ICollection&lt;KeyValuePair&lt;T, V&gt;&gt;

我意识到我也不知道答案。以下是官方文档的链接:

Dictionary&lt;T, V&gt; - http://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx IDictionary&lt;T,V&gt; - http://msdn.microsoft.com/en-us/library/s4ys34ea(v=vs.110).aspx

这样做有什么具体原因吗?是否有特定的架构模式或任何东西?

【问题讨论】:

  • 您无法从文档中看到这一点 - 它显示了所有接口,无论它们是如何实现的。
  • 如果您在谈论显式实现的方法,这些方法是显式的,以避免在类本身上显示它们,而不是因为与 IDictionary 有任何关系。
  • @CodesInChaos 看了你的评论后的源代码,但和文档是一样的。
  • @Selman22 您是指显式列出要从中派生的接口,还是显式实现接口方法?如果接口在 IL 中列出,因此可以在反编译器中看到,这可能是 CIL 和 C# 编译器如何工作的工件。如果它在 ROTOR 源代码中,那么它是 Microsoft 的风格选择,对编译的程序没有影响。

标签: c# .net dictionary


【解决方案1】:

这似乎只是隐式显示所有已实现接口的情况。

我制作了以下示例来测试这一点。我的源代码是:

public class Class1 : ITest
{
    public void Testing()
    {
        Console.WriteLine("Test");
    }

    public void Testing2()
    {
        Console.WriteLine("Test2");
    }
}

public interface ITest : ITest2
{
    void Testing();
}

public interface ITest2
{
    void Testing2();
}

现在进入 Reflector.Net 并反编译我得到了这个:

public class Class1 : ITest, ITest2
{
    public void Testing()
    {
        Console.WriteLine("Test");
    }

    public void Testing2()
    {
        Console.WriteLine("Test2");
    }
}

【讨论】:

    猜你喜欢
    • 2010-09-21
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    相关资源
    最近更新 更多