通用类型标识符转换。如何?

发布于 2024-08-29 15:34:06 字数 639 浏览 8 评论 0原文

如何将 TypeIdenitifier 转换为类类型?我需要使用隐式转换。

type
  TMyChildArray<T>=class(TMyArray<T>)
    private
      FData:Array of T;
      procedure AddEnd();
  end;

  TTypeIdenitifierParentClass=class(TAnotherParentClass)
    protected
      TestField:Cardinal;
  end;


  procedure TMyChildArray<T>.AddEnd();
  var elem:T;
  begin
    for elem in Fdata do
      TTypeIdenitifierParentClass(elem).TestField:=0;
  end;

我在隐式转换“TTypeIdenitifierParentClass(elem).TestField:=0;”上得到“无效类型转换”。

我想要使​​用的原则是 TypeIdenitifier 将表示一个从 TTypeIdenitifierParentClass 派生的类。类类型有很多,但它们都派生于该类。

我该怎么做?

How do I convert the TypeIdenitifier to a class type? I need to use implicit convertion.

type
  TMyChildArray<T>=class(TMyArray<T>)
    private
      FData:Array of T;
      procedure AddEnd();
  end;

  TTypeIdenitifierParentClass=class(TAnotherParentClass)
    protected
      TestField:Cardinal;
  end;


  procedure TMyChildArray<T>.AddEnd();
  var elem:T;
  begin
    for elem in Fdata do
      TTypeIdenitifierParentClass(elem).TestField:=0;
  end;

I get "Invalid typecast" on the implicit convertion "TTypeIdenitifierParentClass(elem).TestField:=0;".

The principle I want to use is that the TypeIdenitifier will represent a class that descends from TTypeIdenitifierParentClass.There are many class types,but all of them descend that class.

How do I do this?

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

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

发布评论

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

评论(1

花开柳相依 2024-09-05 15:34:06

delphi 抱怨转换的原因是编译器无法知道 T 是否可以类型转换为“TTypeIdenitifierParentClass”。您需要将 T 限制为从“TTypeIdenitifierParentClass”降序的类

尝试以下操作

type
  TTypeIdenitifierParentClass=class(TAnotherParentClass)
    protected
      TestField:Cardinal;
  end;

  TMyChildArray<T: TTypeIdenitifierParentClass>=class(TMyArray<T>)
    private
      FData:Array of T;
      procedure AddEnd();
  end;

  procedure TMyChildArray<T>.AddEnd();
  var elem:T;
  begin
    for elem in Fdata do
      elem.TestField:=0;
  end;

The reason delphi is complaining about the cast is because the compiler has no way of knowing if T can be type casted to "TTypeIdenitifierParentClass". You need to limit T to classes descending from "TTypeIdenitifierParentClass"

Try the following

type
  TTypeIdenitifierParentClass=class(TAnotherParentClass)
    protected
      TestField:Cardinal;
  end;

  TMyChildArray<T: TTypeIdenitifierParentClass>=class(TMyArray<T>)
    private
      FData:Array of T;
      procedure AddEnd();
  end;

  procedure TMyChildArray<T>.AddEnd();
  var elem:T;
  begin
    for elem in Fdata do
      elem.TestField:=0;
  end;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文