检查某个值是否在集合中的替代方法

发布于 2024-09-04 17:27:55 字数 439 浏览 3 评论 0原文

我有以下代码。它看起来很难看,如果该值等于以下值之一,则执行某些操作。

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 中的有效集仅接受字节类型的元素。是否有任何好的替代方案来重构我的原始代码(除了用例之外)?

I have the following code. It looks ugly, if the value equals to one of the following value then do something.

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

I want to refactor the code as follows:

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

However, the refactored code does not work. I assume that a valid set in Delphi accepts only elements with type byte. If there any good alternative to refactor my original code (besides using case)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘿看小鸭子会跑 2024-09-11 17:27:55

我想是这样的吗?

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

I think something like this?

case value of
  1, 30000, 40000: do_somthing
end;
夏雨凉 2024-09-11 17:27:55

使用开放数组怎么样?

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;

How about using an open array?

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;

Example (pseudo-code):

var
  Value: Integer;
begin
  Value := ...;
  if ValueIn(Value, [30000, 40000, 1]) then
    ...
end;
帅冕 2024-09-11 17:27:55

有一个用于较大位集的类,请参阅 Classes.TBits。

虽然它不能轻松地执行常量表达式,但它在某些其他情况下可能很有用。

There is a class for larger bitsets, see Classes.TBits.

While it won't do constant expressions easily, it can be useful in certain other cases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文