我如何从Dictionary继承?

Pra*_*are 18 c# collections inheritance

我想要所有的功能,Dictionary<TKey,TValue>但我想要它Foo<TKey,TValue>.
我应该怎么做呢?
目前我正在使用

class Foo<TKey,TValue> : Dictionary<TKey, TValue>
{   
    /*
     I'm getting all sorts of errors because I don't know how to 
     overload the constructors of the parent class.
    */
    // overloaded methods and constructors goes here.

    Foo<TKey,TValue>():base(){}
    Foo<TKey,TValue>(int capacity):base(capacity){}

}
Run Code Online (Sandbox Code Playgroud)

重载父类的构造函数和方法的正确方法是什么?

注意:我认为我滥用了"过载"一词,请更正或建议更正.

Jak*_*son 25

你很接近,你只需要从构造函数中删除类型参数.

class Foo<TKey,TValue> : Dictionary<TKey, TValue>
{   
    Foo():base(){}
    Foo(int capacity):base(capacity){}
}
Run Code Online (Sandbox Code Playgroud)

要覆盖方法,可以使用override关键字.

  • 不在构造函数中,没有...它们已经在类型中,因此它们已经"拥有"类型参数. (2认同)
  • public必须在C#中明确定义,没有它默认为private. (2认同)
  • 如果没有一个方法是虚拟的,那么从Dictionary继承的重点是什么? (2认同)

Ste*_*ger 17

不直接回答你的问题,只是一个建议.我不会继承字典,我会实现IDictionary<T,K>并聚合一个字典.这很可能是一个更好的解决方案:

class Foo<TKey,TValue> : IDictionary<TKey, TValue>
{   

    private Dictionary<TKey, TValue> myDict;

    // ...
}
Run Code Online (Sandbox Code Playgroud)


Sla*_*lai 8

如果您只想要相同的类型但名称不同,则可以使用using别名缩短它:

using Foo = System.Collections.Generic.Dictionary<string, string>;
Run Code Online (Sandbox Code Playgroud)

进而

Foo f = new Foo();
Run Code Online (Sandbox Code Playgroud)