【发布时间】:2012-09-13 21:56:56
【问题描述】:
我可以从一个类中枚举常量(const)吗?
我试过了
MyClass = class
const
c1 = 'c1';
c2 = 'c2';
c3 = 'c3';
end;
procedure GetConst();
var
ctx: TRttiContext;
objType: TRttiType;
field: trttifield;
s: string;
begin
ctx := TRttiContext.Create;
objType := ctx.GetType(MyClass.ClassInfo);
for field in objType.GetDeclaredFields do
s:= field.Name;
end;
我想获得 c1、c2、c2。
这可能吗?
编辑: 我想要做的是为一些外部符号定义一些键(用于 cad 程序)
symbol1=class
const
datafield1='datafield1';
datafield2='datafield2';
end;
symbol2=class
const
datafield21='datafield21abc';
datafield22='datafield22abc';
end
我不喜欢为此使用字段,因为我不喜欢将声明和初始化分开。 我不能使用枚举,因为我不能将值定义为字符串。
【问题讨论】:
-
可能不会。可能在编译时不再有常量,而是立即值。单独保存它们没有什么意义
-
如果你做了一个枚举,你可以将
TypInfo添加到你的uses子句中,然后使用GetEnumName和GetEnumValue在字符串和序数值之间进行转换。 -
但是枚举值只能是整数,对吧?我需要字符串
-
GetEnumName将int转换为string。GetEnumValue将string转换为枚举int。因此,即使枚举是一系列ints,您也可以在代码中像字符串一样使用它们。 -
我将添加一个示例作为答案,以便您了解如何将枚举转换为字符串并返回枚举...