如何比较枚举类型的集合

Tri*_*ber 8 delphi delphi-10.2-tokyo

从某一点来说,我厌倦了编写设置条件(and,or),因为对于更多条件或更长的变量名称,它开始变得笨拙并且令人讨厌再次写入.所以我开始写助手,所以我可以写ASet.ContainsOne([ceValue1, ceValue2])而不是(ceValue1 in ASet) or (ceValue2 in ASet).

type
  TCustomEnum = (ceValue1, ceValue2, ceValue3);
  TCustomSet = set of TCustomEnum;
  TCustomSetHelper = record helper for TCustomSet 
    function ContainsOne(ASet: TCustomSet): Boolean;
    function ContainsAll(ASet: TCustomSet): Boolean;
  end;

implementation

function TCustomSetHelper.ContainsOne(ASet: TCustomSet): Boolean;
var
  lValue : TCustomEnum;
begin
  for lValue in ASet do
  begin
    if lValue in Self then
      Exit(True);
  end;
  Result := False;
end;

function TCustomSetHelper.ContainsAll(ASet: TCustomSet): Boolean;
var
  lValue : TCustomEnum;
begin
  Result := True;
  for lValue in ASet do
  begin
    if not (lValue in Self) then
      Exit(False);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不是最有效的解决方案,而是违反DRY原则.令我惊讶的是,我没有找到任何人处理同样的问题,所以我想知道是否有更好的(通用)解决方案?

Dav*_*nan 15

集合运算符帮你实现这些功能

因为ContainsOne我们使用作为*集合交叉算子的运算符.

function TCustomSetHelper.ContainsOne(ASet: TCustomSet): Boolean;
begin
  Result := ASet * Self <> [];
end;
Run Code Online (Sandbox Code Playgroud)

因为ContainsAll我们会使用<=哪个是子集运算符.

function TCustomSetHelper.ContainsAll(ASet: TCustomSet): Boolean;
begin
  Result := ASet <= Self;
end;
Run Code Online (Sandbox Code Playgroud)

鉴于这些表达式有多简单,我怀疑你是否需要帮助器类型.

文档提供了可用集合运算符的完整列表.


MBo*_*MBo 5

您可以使用设置交集运算符

用于ContainsOne模拟检查交集是否为空集,用于ContainsAll检查交集是否与参数集重合

type
  TCustomEnum = (ceValue1, ceValue2, ceValue3);
  TCustomSet = set of TCustomEnum;
var
  ASet: TCustomSet;
begin
  ASet := [ceValue1, ceValue3];

  if ([ceValue1, ceValue2] *  ASet) <> [] then
     Memo1.Lines.Add('Somebody here');

  if ([ceValue1, ceValue3] *  ASet) = [ceValue1, ceValue3] then
     Memo1.Lines.Add('All are in home');
Run Code Online (Sandbox Code Playgroud)