官术网_书友最值得收藏!

  • Expert Delphi
  • Pawe? G?owacki
  • 267字
  • 2021-07-02 20:44:24

Runtime Type Information

RTTI provides reflection capabilities to the Object Pascal language. With reflection, different types of meta-programming scenarios are possible. You can, for example, write code that will be able to operate on objects that it does not know about. RTTI provides abstractions for all the different types available in the Object Pascal language in the System.Rtti unit that comes with Delphi. All classes and built-in simple types can be treated in a unified way using the TValue record. If you want to programmatically inspect a type and to know whether it is a class and what members it contains, you can use TRttiContext, which has a GetType method that returns an instance of the TRttiType reference, which has methods that let you inspect a given type and iterate through all its members if it is a class.

In our documentation attribute example, we can use RTTI to retrieve documentation URLs for the type itself and for its methods. Refer to the following code snippet:

uses RTTI, uDocAttribute, uMySuperClass; 
 
procedure TFormDemo.Button1Click(Sender: TObject); 
var 
  ctx: TRttiContext; 
  t: TRttiType; 
  m: TRttiMethod; 
  a: TCustomAttribute; 
begin 
  ClearLog; 
 
  ctx := TRttiContext.Create; 
  try 
    t := ctx.GetType(TMySuperClass); 
 
    for a in t.GetAttributes do 
          if a is DocAttribute then 
            Log(Format('Type = %s; Attribute = %s, URL = %s', 
              [TMySuperClass.ClassName, a.ClassName, DocAttribute(a).URL])); 
 
    for m in t.GetMethods do 
      for a in m.GetAttributes do 
        if a is DocAttribute then 
          Log(Format('Type = %s; Method = %s; Attribute = %s, URL = %s', 
            [TMySuperClass.ClassName, m.Name, a.ClassName, DocAttribute(a).URL])); 
 
  finally 
    ctx.Free; 
  end; 
end; 

The RTTI context object owns all the intermediate objects that represent different class members such as TRttiMethod or TRttiAttribute.

主站蜘蛛池模板: 上蔡县| 香河县| 如皋市| 和硕县| 紫阳县| 田阳县| 科技| 宁南县| 信丰县| 基隆市| 保康县| 五家渠市| 县级市| 安义县| 卓尼县| 常山县| 象山县| 永平县| 佳木斯市| 大理市| 崇礼县| 叶城县| 太湖县| 威远县| 达日县| 鄂托克旗| 桂阳县| 德令哈市| 临夏县| 石林| 河东区| 铁岭县| 洞口县| 扶沟县| 淄博市| 新化县| 泊头市| 扎囊县| 泸溪县| 襄汾县| 麻栗坡县|