在C#中,字典本身是可变的,但是可以通过将字典封装在一个不可变的类中来实现不可变的字典。以下是一个简单的示例:
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class ImmutableDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> _dictionary;
public ImmutableDictionary()
{
_dictionary = new Dictionary<TKey, TValue>();
}
public ImmutableDictionary(IDictionary<TKey, TValue> dictionary)
{
_dictionary = new ReadOnlyDictionary<TKey, TValue>(dictionary);
}
public TValue this[TKey key] => _dictionary[key];
public bool ContainsKey(TKey key) => _dictionary.ContainsKey(key);
public bool TryGetValue(TKey key, out TValue value) => _dictionary.TryGetValue(key, out value);
public ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value)
{
var newDictionary = new Dictionary<TKey, TValue>(_dictionary);
newDictionary.Add(key, value);
return new ImmutableDictionary<TKey, TValue>(newDictionary);
}
public ImmutableDictionary<TKey, TValue> Remove(TKey key)
{
var newDictionary = new Dictionary<TKey, TValue>(_dictionary);
newDictionary.Remove(key);
return new ImmutableDictionary<TKey, TValue>(newDictionary);
}
}
这个类实现了一个不可变的字典,可以通过Add
和Remove
方法添加和删除元素,但是这些方法会返回一个新的不可变字典,而不是修改原始字典。这样可以确保字典的不可变性。
需要注意的是,由于这个类使用了ReadOnlyDictionary
来实现只读字典,因此它不能被序列化为JSON或XML格式。如果需要序列化,可以使用其他方法来实现不可变字典。
领取专属 10元无门槛券
手把手带您无忧上云