检查某个值是否在集合中的替代方法
我有以下代码。它看起来很难看,如果该值等于以下值之一,则执行某些操作。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想是这样的吗?
I think something like this?
使用开放数组怎么样?
示例(伪代码):
How about using an open array?
Example (pseudo-code):
有一个用于较大位集的类,请参阅 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.