回傳唯讀狀態的資料結構
在設計 API 的回傳值時,有時會回傳 List 或 Dictionary,但假如這是共用的資料,這時就會希望接收方不要修改內部的值。但在技術上很難避免,甚至會造成邏輯上的錯誤,最後為了找出這錯誤,只能一步步檢視有使用到該回傳值的程式碼。
所幸在 .NET 中有唯讀屬性的相關資料結構可以使用,例如下列程式碼中的 Dictionary:
string key = "key1";
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add(key, "v1");
ReadOnlyDictionary<string, string> r = dict.AsReadOnly();
r[key] = "v1"; //error
IDictionary<string, string> id = r as IDictionary<string, string>;
id[key] = "aaa"; //get exception
id.Add("aa", "aa"); //get exception
如上面的程式碼,在企圖修改值時,編譯器就會產生錯誤,而如果強行轉為 IDictionary 介面然後去改值,則會拋出 Exception。
而 List 也有對應的資料結構:
List<string> list = new List<string>();
ReadOnlyCollection<string> rc = list.AsReadOnly();
rc[0] = "aaa"; //error
參考資料