[英]C# private variable & java private variable getter & setter - Difference?
[英]Is there a difference between having a private setter OR only defining a getter?
我需要創建一個將兩個字典包裝在一起的類,以便可以通過int或string的鍵來檢索它們的值。
屬性似乎是最好的方法,但這兩種實現之間有區別嗎?
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
。 我意識到編譯器會將我的自動屬性搞砸到與頂級代碼塊類似的東西......
引發哪個編譯器錯誤實際上是否重要?
唯一的區別是,在第二種情況下,設置器是不可訪問的,但它在那里,而在第一種情況下根本沒有訪問器。 這意味着使用反射的程序可能會訪問第二個示例的屬性,而在第一個示例的情況下,您需要訪問字段。
就非反射使用而言,兩個代碼片段之間沒有區別:外部類將無法設置字典。
您可能希望更進一步,隱藏類的用戶對詞典的存在。 您可能希望通過將其隱藏在一對方法后面來隱藏類的用戶的實現細節,而不是提供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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.