case 语句中的 Delphi 类型常量
在 Delphi 的 case
语句中使用类型化常量的最优雅(或最不难看)的方式是什么?
也就是说,对于这个问题,假设您需要声明一个类型常量,如“
const
MY_CONST: cardinal = $12345678;
...
Then Delphi 编译器不会接受”
case MyExpression of
MY_CONST: { Do Something };
...
end;
,但您需要编写
case MyExpression of
$12345678: { Do Something };
...
end;
这样的常量,这种常量容易出错、难以更新且不优雅。
您可以使用任何技巧来使编译器插入常量的值(最好通过检查源代码中 const
下的常量值,但也可以通过在运行时查找该值)?我们在这里假设您不会在运行时更改“常量”的值。
What is the most elegant (or least ugly) way of using typed constants in a case
statement in Delphi?
That is, assume for this question that you need to declare a typed constant as in
const
MY_CONST: cardinal = $12345678;
...
Then the Delphi compiler will not accept
case MyExpression of
MY_CONST: { Do Something };
...
end;
but you need to write
case MyExpression of
$12345678: { Do Something };
...
end;
which is error-prone, hard to update, and not elegant.
Is there any trick you can employ to make the compiler insert the value of the constant (preferably by checking the value of the constant under const
in the source code, but maybe by looking-up the value at runtime)? We assume here that you will not alter the value of the "constant" at runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据您需要输入常量的原因,您可以尝试类似的操作
Depending on why you need the constant to be typed you can try something like
如果您不改变常量的值,那么您不需要它是类型常量。编译器可以获取您声明的数字并将其正确放入您分配给它的任何变量或参数中。类型化常量有点像黑客,它们实际上是作为变量实现的,因此编译器不能将它们用作需要在编译时固定值的常量。
If you won't alter the value of the constant, then you don't need it to be a typed constant. The compiler can take the number you declare and correctly place it into whatever variable or parameter you assign it to. Typed constants are sort of a hack, and they're actually implemented as variables, so the compiler can't use them as constants whose value needs to be fixed at compile-time.
类型化常量不能在 case 语句中使用,因为类型化常量实际上更多的是静态变量(并且可赋值...),因此不能在需要常量的 case 语句中使用。
Typed constants can not be used in case statements, because a typed constant is actually more a static variable (and assignable...), and thus can't serve in a case statement, which expects constants.