有什么方法可以拥有一个独特的、只读的集合吗?

问题描述 投票:0回答:1

我有一个这样的大枚举:

public enum RetirementTypes
{
   k401 = 1,
   b403 = 2,
   b457 = 3,
   SimpleIRA = 4,
   Simple401k = 5,
   TIRA = 6,
   RIRA = 7,
   RothIRA = 8,
   Solo401k = 9,
   SEPIRA = 10,
   FA = 11,
   VA = 12,
   ESOP = 14,
   PERA = 15,
   VL = 16,
   SpousalIRA = 17,
   BIRA = 19,
   OtherRetirement = 22,
   TSP = 23,
   OtherIra = 24,
   BRoth = 33
   ...
}//RetirementTypes

我想在我的一些组件中定义这些类型的一些子集。理想情况下,我的列表应该是常量/只读,并包含唯一项,如果我在编译时意识到唯一问题,那就太好了(我怀疑是否有任何解决方案)。

到目前为止我使用

IReadOnlyCollection
。例如,此子集用于识别某些 IRA 类型:

IReadOnlyCollection<RetirementTypes> RETIREMENT_IRA_TYPES = [RetirementTypes.SEPIRA, 
RetirementTypes.BIRA, RetirementTypes.RothIRA, RetirementTypes.OtherIra,RetirementTypes.RIRA, RetirementTypes.SpousalIRA, RetirementTypes.OtherIra, RetirementTypes.RothIRA ...]

它的未来用途是各种查询中的过滤器,例如:

iw.WbRetirements.Where(x => x.Owner == (int)OwnerType.Self && RETIREMENT_IRA_TYPES.Contains((RetirementTypes)x.RetirementPlanType)).Sum(b => b.Balance);
c#
1个回答
1
投票

将@canton7的有用评论变成答案:

听起来像 IReadOnlySet / FrozenSet / ImmutableHashSet 吗? 这些不会给你一个关于非唯一成员的编译时错误, 但他们会在运行时忽略重复的成员,并且包含测试 将是 O(1) 而不是 O(n) (ImmutableHashSet 将是 O(log n)).

据我所知,无法在编译时执行所需的唯一性检查。

© www.soinside.com 2019 - 2024. All rights reserved.