2010-06-07 69 views
8

我有以下代碼。它看起來很醜陋,如果該值等於下面的值之一,那麼做一些事情。替代檢查,值是否在集合中

var 
    Value: Word; 
begin 
    Value := 30000; 
    if (Value = 30000) or (Value = 40000) or (Value = 1) then 
    do_something; 
end; 

我想如下重構代碼:

var 
    Value: Word; 
begin 
    Value := 30000; 
    if (Value in [1, 30000, 40000]) then // Does not work 
    do_something; 
end; 

然而,重構的代碼無法正常工作。我假定Delphi中的一個有效集合只接受類型爲byte的元素。如果有什麼好的替代方案來重構我的原始代碼(除了使用案例)?

回答

15

我覺得這樣?

case value of 
    1, 30000, 40000: do_somthing 
end; 
+1

謝謝,但正如我在我的問題中指出的,我想要另一種選擇。因爲使用開關...這種邏輯的情況看起來不正常 – stanleyxu2005 2010-06-07 08:34:33

+0

@ stanleyxu2005。這可能是最有效的。另外,當你開始寫這樣的東西時,如果條件'如果[。]中的值做了bla,否則如果在[..]中有值,你很可能最終不得不添加一個else或者else else條件。做blabla別人做blablabla'。在這種情況下,案件是明顯的選擇。 – 2010-06-07 17:05:14

+0

經過一天的等待迴應,我同意使用switch ... case是最可接受的解決方案。 – stanleyxu2005 2010-06-07 18:32:50

13

如何使用開放數組?

function ValueIn(Value: Integer; const Values: array of Integer): Boolean; 
var 
    I: Integer; 
begin 
    Result := False; 
    for I := Low(Values) to High(Values) do 
    if Value = Values[I] then 
    begin 
     Result := True; 
     Break; 
    end; 
end; 

實施例(僞代碼):

var 
    Value: Integer; 
begin 
    Value := ...; 
    if ValueIn(Value, [30000, 40000, 1]) then 
    ... 
end; 
+1

+1,不錯,我喜歡可重用性和清潔度。 – 2010-06-07 09:49:09

1

有較大位集的一類,見Classes.TBits。

儘管它不會輕鬆地進行常量表達,但在某些其他情況下它可能很有用。