我需要创建一个包含两个字典的类,以便可以通过 int 或字符串的键来检索它们的值。
属性似乎是最好的方法,但这两种实现之间有区别吗?
public class Atlas<TValue>
{
private Dictionary<int, TValue> _byIndex;
private Dictionary<string, TValue> _byName;
public Dictionary<int, TValue> ByIndex
{
get { return _byIndex; }
}
public Dictionary<string, TValue> ByName
{
get { return _byName; }
}
}
和
public class Atlas<TValue>
{
public Dictionary<int, TValue> ByIndex { get; private set; }
public Dictionary<string, TValue> ByName { get; private set; }
}
在任何一种情况下,字典对象都是不可变的,元素可以自由更改,这就是我想要的。但是,尝试更改字典对象将导致~ cannot be assigned to -- it is read only
或~ cannot be used in this context because the set accessor is inaccessible
。我意识到编译器会将我的自动属性弄为类似于顶级代码块的东西......
引发哪个编译器错误实际上是否重要?
答案 0 :(得分:4)
唯一的区别是,在第二种情况下,设置器是不可访问的,但它在那里,而在第一种情况下根本没有访问器。这意味着使用反射的程序可能会访问第二个示例的属性,而在第一个示例的情况下,您需要访问字段。
就非反思使用而言,两个代码片段之间没有区别:外部类将无法设置字典。
您可能希望进一步隐藏类别用户的词典。您可能希望通过将其隐藏在一对方法后面隐藏类的用户,而不是提供Dictionary
类型的两个属性:
public class Atlas<TValue> {
public bool TryGetByIndex(int index, out TValue val);
public void Add(int index, TValue val);
public bool TryGetByName(string name, out TValue val);
public void Add(string name, TValue val);
public TValue this[string name] { get ... set ...}
public TValue this[int index] { get ... set ...}
// You may want to add more methods or properties here, for example to iterate atlas elements
}