给定以下类:
public static class ComboModel
{
public static Dictionary<int, int[]> Items()
{
return new Dictionary<int, int[]>
{
{
1,
new[] {
2,
3,
4
}
}
};
}
}
我想确保类中数据的不变性,但这感觉像 javascript 并且引起了我的同行的一些含糊(但强烈)的批评。有什么问题吗?
请您参考如下方法:
只需使用 ReadOnlyDictionary,并且只分配一次:
public static class ComboModel {
private static readonly ReadOnlyDictionary<int, int[]> _items = new ReadOnlyDictionary<int, int[]>(new Dictionary<int, int[]> {
{
1,
new[] {
2,
3,
4
}
}
});
public static IReadOnlyDictionary<int, int[]> Items
{
get { return _items; }
}
}
请注意,正如其他人已经提到的那样,您不仅在每次调用时都分配了新实例 - 您还会给调用者提供一种错误的感觉,即他可以修改该字典。在 ReadOnlyDictionary 中没有可以修改它的方法。 当调用者知道它接收到的结构无法更改时,还有其他好处:例如,他可以使用多个线程安全地处理那里的项目。
更新:当然,只读集合不会神奇地使存储在该集合中的对象只读 - 只是集合本身。如果您想确保示例中 int[] 数组的不变性,只需将它们也设置为只读即可:
public static class ComboModel {
private static readonly IReadOnlyDictionary<int, ReadOnlyCollection<int>> _items = new ReadOnlyDictionary<int, ReadOnlyCollection<int>>(new Dictionary<int, ReadOnlyCollection<int>> {
{
1,
Array.AsReadOnly(new[] {
2,
3,
4
})
}
});
public static IReadOnlyDictionary<int, ReadOnlyCollection<int>> Items
{
get { return _items; }
}
}
