不可变字典< TKey,TValue> [英] Immutable Dictionary<TKey, TValue>
本文介绍了不可变字典< TKey,TValue>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何为不可变的Dictionary<TKey, TValue>
类实现构造函数?
How would you implement constructors for an immutable Dictionary<TKey, TValue>
-like class?
还可以允许用户使用以下语法:
Also, is it possible to allow users to use the syntax:
ImmutableDic<int, int> Instance = new ImmutableDic<int, int> { {1, 2}, {2, 4}, {3,1} };
推荐答案
最简单的解决方案是编写一个接受可变IDictionary<TKey, TValue>
的构造函数.构建可变字典,然后将其传递给不可变字典的构造函数:
The simplest solution is to write a constructor that accepts a mutable IDictionary<TKey, TValue>
. Build the mutable dictionary and just pass it to the constructor of your immutable dictionary:
var data = new Dictionary<int, int> { {1, 2}, {2, 4}, {3,1} };
var instance = new ImmutableDic<int, int>(data);
如BoltClock的注释中所述,初始化器语法不能与不可变字典一起使用,因为它需要Add
方法.
As explained in BoltClock's comment, the initializer syntax can't be used with an immutable dictionary, since it requires an Add
method.
这篇关于不可变字典< TKey,TValue>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文