Rtti 不适用于用作类字段的泛型类型

发布于 2024-12-20 05:48:07 字数 1133 浏览 2 评论 0原文

我在使用 rtti 获取有关泛型类型的类字段的信息时遇到问题。经过一番谷歌搜索后,我在 QC 中找到了一个条目,描述了的问题。我的问题是,是否有人知道解决方法,或者是否已修复 Delphi XE2。以下是 QC 重现该错误的源代码片段。

program Generics;

    {$APPTYPE CONSOLE}

    uses
       Generics.Collections, Rtti, SysUtils;

    type
       TIntList = TList<Integer>;

       TRecContainer = record
         FList: TIntList;
       end;

       TObjContainer = class
         FList: TIntList;
       end;

    var
       ctx: TRttiContext;
       f: TRttiField;

    begin
       ctx := TRttiContext.Create;
       try
         for f in ctx.GetType(TypeInfo(TRecContainer)).GetFields do
           if f.FieldType <> nil then
             writeln(f.FieldType.Name)
           else
             writeln('f.FieldType = nil');
         for f in ctx.GetType(TypeInfo(TObjContainer)).GetFields do
           if f.FieldType <> nil then
             writeln(f.FieldType.Name)
           else
             writeln('f.FieldType = nil');
       finally
         ctx.Free;
         readln;
       end;
    end.

I had problems using rtti to get information about class fields of a generic type. After quite some googleing I found an entry in QC describing the issue. My question is, if anybody knows a workaround, or if this got fixed Delphi XE2. Below is the source snippet from QC to reproduce the bug.

program Generics;

    {$APPTYPE CONSOLE}

    uses
       Generics.Collections, Rtti, SysUtils;

    type
       TIntList = TList<Integer>;

       TRecContainer = record
         FList: TIntList;
       end;

       TObjContainer = class
         FList: TIntList;
       end;

    var
       ctx: TRttiContext;
       f: TRttiField;

    begin
       ctx := TRttiContext.Create;
       try
         for f in ctx.GetType(TypeInfo(TRecContainer)).GetFields do
           if f.FieldType <> nil then
             writeln(f.FieldType.Name)
           else
             writeln('f.FieldType = nil');
         for f in ctx.GetType(TypeInfo(TObjContainer)).GetFields do
           if f.FieldType <> nil then
             writeln(f.FieldType.Name)
           else
             writeln('f.FieldType = nil');
       finally
         ctx.Free;
         readln;
       end;
    end.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤星 2024-12-27 05:48:07

不幸的是,这个错误在 Delphi XE2 中仍然存在,作为解决方法,您可以像这样声明 TIntList 类型

TIntList = class(TList<Integer>);

Unfortunally this bug is still present in Delphi XE2, as Workaround you can declare the TIntList type like this

TIntList = class(TList<Integer>);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文