给定 Delphi 中的枚举类型声明,例如:
TMyType = (Item1, Item2, Item3);
有没有办法在运行时将第四个项目(例如 Item4)添加到枚举类型,以便 在应用程序执行期间的某个时刻,我有:
TMyType = (Item1, Item2, Item3, Item4);
或者 Delphi 中的类型是固定的吗?
最佳答案
您可以创建一个集合
。
以下示例使用项目 item1
和 item4
初始化集合。
之后添加 item5
。
它显示了添加之前和之后 item5 是否在集合中,因此您将得到以下输出:
FALSE
TRUE
示例:
program Project1;
{$APPTYPE CONSOLE}
uses SysUtils;
type
TMyType = (Item1, Item2, Item3, Item4, Item5,Item6);
const
cItems1And4 : set of TMyType = [Item1,Item4];
var
MyItems:set of TMyType;
begin
MyItems := cItems1And4;
WriteLn(Item5 in MyItems);
Include(MyItems,Item5);
WriteLn(Item5 in MyItems);
ReadLn;
end.
...
我想输入以下内容作为对 Andreases 回复的评论,但评论系统不允许我正确格式化内容。
如果您不沉迷于古老的 Delphi,这可能是一个更好的主意:
TComputerType = record
const
Desktop = 0;
Server = 1;
Netbook = 2;
Tabled = 3;
end;
这可以确保您不会污染您的命名空间,并且您可以像使用作用域枚举一样使用它:
TComputerType.Netbook
现在我通常这样做。您甚至可以在其中创建一些方便的辅助函数或属性,例如从字符串转换为字符串。
关于delphi - 向枚举类型添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7248222/