首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Delphi XE中的类型转换问题

Delphi XE中的类型转换问题
EN

Stack Overflow用户
提问于 2011-09-15 05:13:06
回答 2查看 1.2K关注 0票数 2

我试着用这样的方式来做程序清单:

代码语言:javascript
复制
type

TProc = procedure of object;

TMyClass=class
private
fList:Tlist;
function getItem(index:integer):TProc;
{....}
public
{....}
end;
implementation
{....}
function TMyClass.getItem(index: Integer): TProc;
begin
 Result:= TProc(flist[index]);// <--- error is here!
end;
{....}
end.

并得到错误:

E2089无效类型广播

我怎么才能修好它?正如我所看到的,我可以只使用一个属性Proc:TProc;创建一个假类,并列出它的列表。但我觉得这不是个好办法,不是吗?

PS:项目必须与Delphi-7兼容.

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-15 16:22:22

类型广播无效,因为无法匹配指向指针的方法指针,方法指针实际上是两个指针,第一个指针是方法的地址,第二个指针是对方法所属对象的引用。请参阅文档中的程序类型。这在Delphi的任何版本中都是行不通的。

票数 5
EN

Stack Overflow用户

发布于 2011-09-15 17:02:43

Sertac解释了为什么您的代码不能工作。为了在Delphi 7中实现这类事情的列表,您可以这样做。

代码语言:javascript
复制
type
  PProc = ^TProc;
  TProc = procedure of object;

  TProcList = class(TList)
  private
    FList: TList;
    function GetCount: Integer;
    function GetItem(Index: Integer): TProc;
    procedure SetItem(Index: Integer; const Item: TProc);
  public
    constructor Create;
    destructor Destroy; override;
    property Count: Integer read GetCount;
    property Items[Index: Integer]: TProc read GetItem write SetItem; default;
    function Add(const Item: TProc): Integer;
    procedure Delete(Index: Integer);
    procedure Clear;
  end;

type
  TProcListContainer = class(TList)
  protected
    procedure Notify(Ptr: Pointer; Action: TListNotification); override;
  end;

procedure TProcListContainer.Notify(Ptr: Pointer; Action: TListNotification);
begin
  inherited;
  case Action of
  lnDeleted:
    Dispose(Ptr);
  end;
end;

constructor TProcList.Create;
begin
  inherited;
  FList := TProcListContainer.Create;
end;

destructor TProcList.Destroy;
begin
  FList.Free;
  inherited;
end;

function TProcList.GetCount: Integer;
begin
  Result := FList.Count;
end;

function TProcList.GetItem(Index: Integer): TProc;
begin
  Result := PProc(FList[Index])^;
end;

procedure TProcList.SetItem(Index: Integer; const Item: TProc);
var
  P: PProc;
begin
  New(P);
  P^ := Item;
  FList[Index] := P;
end;

function TProcList.Add(const Item: TProc): Integer;
var
  P: PProc;
begin
  New(P);
  P^ := Item;
  Result := FList.Add(P);
end;

procedure TProcList.Delete(Index: Integer);
begin
  FList.Delete(Index);
end;

procedure TProcList.Clear;
begin
  FList.Clear;
end;

免责声明:完全未经测试的代码,使用自己的风险。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7426137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档