Adding new elements to an enumerated type
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?
You can create a set
.
The following example initializes the set with items item1
and item4
.
After that item5
is added.
It shows whether item5 is in the set, before and after adding, so you'll get this output:
FALSE
TRUE
Example:
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.
...
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:
TComputerType = record
const
Desktop = 0;
Server = 1;
Netbook = 2;
Tabled = 3;
end;
That makes sure you don't pollute your namespace, and you'll get to use it as if it's a scoped enum:
TComputerType.Netbook
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.
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
TComputerType = (ctDesktop, ctServer, ctLaptop, ctNetbook, ctTablet)
Instead, I'd do
TComputerType = integer;
const
COMPUTER_TYPE_DESKTOP = 0;
COMPUTER_TYPE_SERVER = 1;
COMPUTER_TYPE_LAPTOP = 2;
COMPUTER_TYPE_NETBOOK = 3;
COMPUTER_TYPE_TABLET = 4;
I am sure you get why.
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:
type
TEnum = (item1, item2, item3, item4);
TSubRangeEnum = item1..item3;
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).
TComputerType = integer;
const
COMPUTER_TYPE_BASE = 100;
COMPUTER_TYPE_DESKTOP = COMPUTER_TYPE_BASE + 1;
COMPUTER_TYPE_SERVER = COMPUTER_TYPE_BASE + 2;
COMPUTER_TYPE_LAPTOP = COMPUTER_TYPE_BASE + 3;
COMPUTER_TYPE_NETBOOK = COMPUTER_TYPE_BASE + 4;
COMPUTER_TYPE_TABLET = COMPUTER_TYPE_BASE + 5;
精彩评论