带有默认值的.net词典 [英] .net dictionary with default value

查看:92
本文介绍了带有默认值的.net词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个字典,该字典将为不在字典中的任何键返回指定值,例如:

I want a dictionary that would return a specified value for any key not in the dictionary, something like:

var dict = new DictWithDefValues("not specified");
dict.Add("bob78", "Smart");
dict.Add("jane17", "Doe");
Assert.AreEqual(dict["xxx"], "not specified");

扩展System.Collections.Generics.Dictionary并覆盖TryGetValue不起作用,因为TryGetValue不是虚拟的.

Extending System.Collections.Generics.Dictionary and overriding TryGetValue doesn't work because TryGetValue isn't virtual.

从头开始重新实现字典(从IDictionary <,>开始)是很费力的.

Reimplementing Dictionary from scratch (from IDictionary<,>) is too much efforts.

扩展方法不允许我使用默认值初始化"字典.我希望字典的使用者认为键在那里,而不仅仅是dict.GetOrDefault(key, "not specified");

Extension method won't let me "initialize" the dictionary with a default value. I want the consumer of dictionary to think that key is there, not just do dict.GetOrDefault(key, "not specified");

推荐答案

从头开始重新实现字典(从IDictionary <,>开始)是很费力的

Reimplementing Dictionary from scratch (from IDictionary<,>) is too much efforts

这确实是最好的选择.只需将Dictionary<,>封装为类的成员,然后将所有成员传递给Dictionary的代码即可.在这种情况下,您只需要处理希望有所不同的属性和方法即可.

This is really the best option. Just encapsulate a Dictionary<,> as a member of your class, and pass all members to the Dictionary's code. You only need to handle the properties and methods you wish to be different in that case.

我同意这是一件繁琐的工作-但由于可以将每种方法都传递给内部字典的实现,因此大概只需不到5分钟的输入时间.

I agree that it's a bit of tedious work - but it's probably less than 5 minutes worth of typing, since every method can be passed to the internal dictionary's implementation.

这篇关于带有默认值的.net词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆