组合的“检查添加或获取”来自字典
我厌倦了这种字典习惯用法:
Dictionary<Guid,Contact> Contacts;
//...
if (!Contacts.ContainsKey(id))
{
contact = new Contact();
Contacts[id] = contact;
}
else
{
contact = Contacts[id];
}
如果有一种语法允许从默认构造函数隐式创建新值(如果它不存在),那就太好了(毕竟字典知道值的类型)。有人见过这样做的助手(例如扩展方法)吗?
I'm tired of this dictionary idiom:
Dictionary<Guid,Contact> Contacts;
//...
if (!Contacts.ContainsKey(id))
{
contact = new Contact();
Contacts[id] = contact;
}
else
{
contact = Contacts[id];
}
It would be nice if there was a syntax that permitted the new value to be created implicitly from a default constructor if it does not exist (the dictionary knows the type of the value, after all). Anyone seen a helper (such as an extension method) that does this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现:
使用:
Implementation:
Usage:
与 Ani 的答案相同,但用了更难以理解的一句话:)
提供一个委托作为值创建者而不是值本身,以防止不必要的对象创建。
字典,不幸的是,没有开箱即用的功能来在一次查找中完成所有这些< /a>.
Same as Ani's answer, but in a more unintelligible one-liner :)
Provide a delegate as value creator than value itself to prevent unnecessary object creation.
Dictionary, unfortunately, doesn't have this feature out of the box to do all this in a single lookup.
您随时可以滚动自己的字典。
解决方案 1:继承并使用“新”重写方法,首先检查是否包含密钥。如果是,则通过键返回该值或由委托创建
。但是,当通过接口使用此字典时,此解决方案将中断,
因此您需要通过解决方案 2 进行更彻底的解决方案。
解决方案 2:使用内部字典的字典包装器 - 其余部分与解决方案 1 相同。解决
方案 3:ConcurrentDictionary提供 GetOrAdd,它也是线程安全的。
解决方案 4:ConcurrentDictionary 包装器类似于解决方案 2。
这是一个字典包装器:
You can always roll your own dictionary.
Solution 1: Inherit and use "new" overriding methods checking first for containing key. If yes return that value by key or create by a
delegate. However, this solution will break when using this dictionary via the interface
So for that you need to be more thorough via solution 2.
Solution 2: Dictionary Wrapper which uses an internal dictionary - the rest is the same as solution 1.
Solution 3: ConcurrentDictionary offers GetOrAdd which is also thread safe.
Solution 4: ConcurrentDictionary Wrapper similar to solution 2.
Here's a dictionary wrapper: