问题
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