0

I'm working in C# and I'm not quite sure how to word this question (which made it hard to search). Basically I have a class that inherits from Dictionary<string,MyButton>, where MyButton is a class I made. However I want to overwrite the Add function to prevent adding keyvalue pairs that don't meet specific requirements (e.x. all MyButton values in the dictionary have size properties of which are all the same). I know how to overwrite the Add function with the New operator however I'm not sure how to overwrite the constructor of the Dictionary class that allows one to do this, for example:

    Dictionary<string, int> d = new Dictionary<string, int>()
    {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };

(Example taken from here)

I'm not sure which constructor allows you to do the above. I believe it's this constructor but I'm not sure how to override it, or even how to make one.

Any help would be appreciated.

Thanks!

4

2 回答 2

2

您提供的代码示例使用对象初始化程序。这就是所谓的编译器“糖”,即它是一种简写语法,可以扩展为等价的长写语法。在这种情况下,它是以下内容的简写:

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("cat", 2);
d.Add("dog", 10);
d.Add("llama", 0);
d.Add("iguana", -1);

因此,在这种情况下使用的是字典的无参数构造函数。

此外,使用new关键字隐藏超类方法而不是覆盖它。我不会推荐它。请参阅此相关问题:

覆盖 Dictionary.Add

于 2012-12-05T06:39:26.923 回答
0

看看KeyedCollection{TKey, TItem}类。它旨在用作键值集合的基类。然后,您可以覆盖受保护的方法 InsertItem、RemoveItem、ClearItems 和 SetItem 以添加您的自定义逻辑。这些方法由 Add、Remove 和 Clear 方法调用。看第二个例子。

于 2012-12-05T10:32:34.683 回答