使用RTTI从类中获取常量字段 [英] Get constant fields from a class using RTTI

查看:62
本文介绍了使用RTTI从类中获取常量字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以从类中枚举常量(const)吗?

Can I enumerate the constants(const) from a class?

我尝试过

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.

I would like to get c1, c2, c2.

这可能吗?

我想做的是为一些外部符号定义一个键(对于cad程序)

edit: what I want to do is define some keys for some external symbols(for a cad program)

symbol1=class
    const
    datafield1='datafield1';
    datafield2='datafield2';
end;
symbol2=class
    const
    datafield21='datafield21abc';
    datafield22='datafield22abc';
end

我不喜欢为此使用字段,因为我不想将声明和初始化分开.我无法使用枚举,因为无法将值定义为字符串.

I don't like to use fields for this because I prefer not to seperate declareration and initialization. I can't use an enum since I can't define the value as a string.

推荐答案

您无法通过RTTI获得这些常量.我怀疑您最好的解决方案是改为使用属性.这不仅会带来实际工作的好处,而且我认为这听起来像是一种更干净,更简单的解决方案.

You can't get at those constants through RTTI. I suspect your best solution will be to use attributes instead. Not only will that have the benefit of actually working, I think it sounds like a cleaner and simpler solution to your problem.

这篇关于使用RTTI从类中获取常量字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆