C# 我如何从字典继承?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1594997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:09:54  来源:igfitidea点击:

How do I inherit from Dictionary?

c#inheritancecollections

提问by Pratik Deoghare

I want all the functionality of Dictionary<TKey,TValue>but I want it as Foo<TKey,TValue>.
How should I go about doing this?
Currently I am using

我想要 的所有功能,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){}

}

What is the right way to overload constructors and methods of the parent class?

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

NOTE:I think I have misused the word 'overload' please correct it or suggest correction.

注意:我想我误用了“过载”这个词,请更正或建议更正。

采纳答案by Jake Pearson

You were close, you just need to remove the type parameters from the constructors.

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

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

To override a method you can use the override keyword.

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

回答by Stefan Steinegger

Not directly answering your question, just an advice. I would not inherit the dictionary, I would implement IDictionary<T,K>and aggregate a Dictionary. It is most probably a better solution:

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

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

    private Dictionary<TKey, TValue> myDict;

    // ...
}

回答by Slai

If you just want the same type but with a different name, you can shorten it with usingalias:

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

using Foo = System.Collections.Generic.Dictionary<string, string>;

and then

进而

Foo f = new Foo();