本文介绍了枚举常量记录字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用RTTi时遇到了一些问题。我想枚举Record类型的所有常量值
I got some problems with RTTi .. i wana to enumerate all constans values in Record type
type TMyRecord = record
const
value1: Integer=10;
value2: Integer=13;
value3: Integer=18;
value4: Integer=22;
end;
procedure TForm3.Button1Click(Sender: TObject);
var
ctx:TRttiContext ;
Field:rtti.TRttiField ;
begin
for Field in ctx.GetType(TypeInfo(TMyRecord)).GetFields do
ListBox1.Items.Add(Field.Name ); // i got nothing
end;
但是当我的Record不是const时,我的代码可以正常工作
but when my Record is not a const , my code work fine
type TMyRecord = record
value1: Integer;
value2: Integer;
value3: Integer;
value4: Integer;
end;
procedure TForm3.Button1Click(Sender: TObject);
var
ctx:TRttiContext ;
Field:rtti.TRttiField ;
begin
for Field in ctx.GetType(TypeInfo(TMyRecord)).GetFields do
ListBox1.Items.Add(Field.Name ); //its work
end;
推荐答案
RTTI无法枚举常量。尽管它们似乎是字段,但实际上不是。它们的实现与记录常量中的任何其他常量一样。
RTTI cannot enumerate constants. Whilst they might appear to be fields, they are not. They are implemented just like any other constant, inside the record's namespace.
您可能需要考虑另一种方法。例如,您可以使用属性代替常量。或者也许添加一个枚举这些常量的类函数。
You may have to consider an alternative approach. For example you could use attributes instead of constants. Or perhaps adding a class function that enumerates these constants.
另一种方法是这样的:
type
TMyRecord = record
value1: Integer;
value2: Integer;
value3: Integer;
value4: Integer;
end;
const
MyConst: TMyRecord = (
value1: 10;
value2: 13;
value3: 18;
value4: 22
);
这篇关于枚举常量记录字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!