向枚举类型添加新元素
给定 Delphi 中的枚举类型声明,例如:
TMyType = (Item1, Item2, Item3);
有没有办法在运行时将第四个项目(例如 Item4)添加到枚举类型,以便 在应用程序执行期间的某个时刻,我有:
TMyType = (Item1, Item2, Item3, Item4);
或者 Delphi 中的类型是固定的吗?
Given an enumerated type declaration in Delphi such as:
TMyType = (Item1, Item2, Item3);
is there any way to add a fourth item, say Item4, to the enumerate type at runtime so that
at some point during the application's execution I have:
TMyType = (Item1, Item2, Item3, Item4);
Or are types fixed in Delphi?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以创建一个
集
。以下示例使用项目
item1
和item4
初始化该集。之后添加
item5
。它显示了添加之前和之后的 item5 是否在集合中,因此您将得到以下输出:
示例:
...
我想输入以下内容作为对 Andreases 回复的评论,但评论系统不允许我正确输入格式的东西..
如果你不坚持使用古老的Delphi,这可能是一个更好的主意:
这确保你不会污染你的命名空间,并且你可以像使用作用域枚举一样使用它:
我通常现在就这样做..你甚至可以在那里创建一些方便的辅助函数或属性,例如从字符串转换到字符串。
You can create a
set
.The following example initializes the set with items
item1
anditem4
.After that
item5
is added.It shows whether item5 is in the set, before and after adding, so you'll get this output:
Example:
...
I wanted to type the following as a comment to Andreases reply, but the comment system doesn't let me properly format stuff..
If you're not stuck with an ancient Delphi, this is probably a better idea:
That makes sure you don't pollute your namespace, and you'll get to use it as if it's a scoped enum:
I usually do it like that nowadays.. You can even create some handy helper-functions or properties in there, for example to convert from and to strings.
不,你“不能”这样做。这违背了 Delphi 的工作方式。 (回想一下,Delphi 在编译时就已经检查了您的类型。)
如果我是您,我不会这样做,
相反,我会这样做,
我相信您明白原因。
No, you 'can't' do this. It is against the way Delphi works. (Recall that Delphi checks your types already at compile time.)
If I were you, I'd not do
Instead, I'd do
I am sure you get why.
在 Delphi 中,类型在编译时就已确定——毕竟,它是一种静态类型语言。
您可以在编译时定义枚举的子范围:
Types are fixed at compile time in Delphi—it is, after all, a statically typed language.
You can, at compile time, define subranges of an enumeration:
由于我还无法发表评论,因此我将在 Andreas 建议的内容中添加一份附录,如果您有许多此类列表需要维护,这可能会有所帮助。为每个分组添加一个“基”常量可能有助于在代码中更好地组织它们,并有助于稍后调试常量(当然,假设每个组都有一个唯一的基)。
Since I cannot yet comment, I will add one addendum to what Andreas suggested that might help if you have many such lists to maintain. Adding a "base" constant for each grouping might help keep them better organized within your code and help with debugging the constants later (assuming each group has a unique base, of course).