現在我有一個 const 字符串數組并循環檢查值是否存在。但我想要一種更有效的方式來存儲我的價值。我知道有一個哈希集,我可以這樣使用:HashSet<string> tblNames = new HashSet<string> ();
tblNames.Add("a");
tblNames.Add("b");
tblNames.Add("c");但是,是否可以像這樣使它成為我班級的常量成員:public const HashSet<string> tblNames = new HashSet<string>() { "value1", "value2" };
1 回答
人到中年有點甜
TA貢獻1895條經驗 獲得超7個贊
創建“常量”Set 的最佳方法可能是使用以下方法將您的接口公開HashSet為它的IEnumerable接口:
public static readonly IEnumerable<string> fruits = new HashSet<string> { "Apples", "Oranges" };public: 每個人都可以訪問它。static:無論創建了多少個父類實例,內存中只會有一個副本。readonly: 您不能將其重新分配給新值。IEnumerable<>:您只能遍歷其內容,而不能添加/刪除/修改。
要進行搜索,您可以使用 LINQ 來調用Contains()您的IEnumerable,它足夠聰明,知道它由 a 支持HashSet并委托適當的調用以利用您的集合的散列特性。(嗯,好吧,它通過 ICollection 調用它,但最終還是以 HashSet 的重寫方法結束)
Debug.WriteLine(fruits.Contains("Apples")); // True
Debug.WriteLine(fruits.Contains("Berries")); // False
fruits = new HashSet<string>(); // FAIL! readonly fields can't be re-assigned
fruits.Add("Grapes"); // FAIL! IEnumerables don't have Add()
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消
