Immutable Dictionary<TKey, TValue>

不羁的心 提交于 2019-12-13 17:52:58

问题


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} };

回答1:


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);

As explained in BoltClock's comment, the initializer syntax can't be used with an immutable dictionary, since it requires an Add method.




回答2:


Have the constructor accept an IEnumerable<KeyValuePair<TKey, TValue>>.

This way, you can do:

var Instance = new ImmutableDic<int, int>(
   new Dictionary<int, int> {1, 2}, {2, 4}, {3,1} });

You can construct with the "minimal" addition of "new Dictionary", and you can also use any other way that is convenient and produces such an enumerable sequence.



来源:https://stackoverflow.com/questions/5427338/immutable-dictionarytkey-tvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!