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
How do I inherit from Dictionary?
提问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;
// ...
}