假设我有一个Composite
由仪器和重量字典构成的类。
public IReadOnlyDictionary<Instrument, double> Underlyings{ get; private set; }
public Composite(
Id id,
Currency currency,
Dictionary<Instrument, double> underlyings
)
{
Underlyings= underlyings;
}
}
此类向客户端公开,我希望客户端能够修改 中现有键的值Underlyings
,但不向Underlyings
.
然后制作Underlyings
aReadOnlyDictionary
将不起作用,因为客户端代码将无法修改现有键的值。所以我的解决方案是从这个答案中获取字典的包装器并修改设置器以便TValue IDictionary<TKey, TValue>.this[TKey key]
可以修改现有值。但这似乎是一个愚蠢的解决方案 - 有没有比编写包装类更简单的方法来拥有一个字典,该字典具有可修改的现有键值对,但不能添加新的键值对?为这个非常简单的问题道歉。