c# - 如何在 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" };
解决方案
创建“常量”集的最佳方法可能是将您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()
推荐阅读
- android - 传输到 GL 线程时,vector3f 中的数据丢失/损坏
- javascript - 获取返回 JSON 的外部 API 时出现问题
- java - 大型阵列反序列化期间的性能下降
- java - 发送 DELETE 时实现状态 200
- python - 实时 ECS 登录 Cloudwatch
- typescript - “字符串”类型上不存在属性“trimLeft”。库:[“dom”,“es2018”]
- python - 将过去 5 个月的 Dataframe 划分为当前月份的 5 个不同的 df?
- primefaces - 在 PrimeFaces 中导出 p:datatable 到 excel
- tfs - SonarQube 上的拉取请求分析和质量门
- python - 如何将 pathlib 与子进程一起使用