从某个时刻开始,我厌倦了编写设定条件(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;
不幸的是,这不是最有效的解决方案,并且违反了 DRY 原则。令我惊讶的是,我没有发现有人处理过同样的问题,所以我想知道是否有更好的(通用)解决方案?
The 集合运算符 http://docwiki.embarcadero.com/RADStudio/en/Expressions_(Delphi)#Set_Operators帮助您实现这些功能
For ContainsOne
我们使用*
运算符是集合交集运算符。
function TCustomSetHelper.ContainsOne(ASet: TCustomSet): Boolean;
begin
Result := ASet * Self <> [];
end;
For ContainsAll
我们会用<=
这是子集运算符。
function TCustomSetHelper.ContainsAll(ASet: TCustomSet): Boolean;
begin
Result := ASet <= Self;
end;
鉴于这些表达式非常简单,我怀疑您是否根本不需要辅助类型。
The 文档 http://docwiki.embarcadero.com/RADStudio/en/Expressions_(Delphi)#Set_Operators给出可用集合运算符的完整列表.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)