delphi - 向枚举类型添加新元素

标签 delphi types enumeration

给定 Delphi 中的枚举类型声明,例如:

TMyType = (Item1, Item2, Item3);

有没有办法在运行时将第四个项目(例如 Item4)添加到枚举类型,以便 在应用程序执行期间的某个时刻,我有:

TMyType = (Item1, Item2, Item3, Item4);

或者 Delphi 中的类型是固定的吗?

最佳答案

您可以创建一个集合

以下示例使用项目 item1item4 初始化集合。 之后添加 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/

相关文章:

delphi - 什么是TExternalThread? "Cannot terminate externally created thread"终止基于线程的计时器时

haskell - 如何制作 Applicative 的固定长度向量实例?

scala - 存在类型之间的映射

c++ - 不稳定类型特征背后的原因是什么?

vector - 如何通过枚举定义并静态初始化向量索引?

delphi - 我需要知道一种方法来确定文件是以独占模式还是以其他方式(读写等)打开?

delphi - 透明 Png 转 TBitmap32

delphi - 如何获取 TWinControl 的 X、Y 位置(相对于屏幕)

java - 在 Java 8 中迭代枚举

C# 列表和枚举器的属性