从某个时候开始,我厌倦了编写条件语句(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原则。令我惊讶的是,我没有找到任何人处理过相同的问题,所以我想知道是否有更好(通用)的解决方案?