首页 > 解决方案 > 如何在 C# 中创建常量哈希集

问题描述

现在我有一个 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" };

标签: c#hashset

解决方案


创建“常量”集的最佳方法可能是将您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()

推荐阅读