您现在的位置:首页 >> 基础算法 >> window基础 >> 内容

Delphi检测对象有方法时是否为纯虚函数

时间:2011/9/3 15:37:10 点击:

  核心提示:下面的方法获得virtual方法的数量,下面是高手的思想对话,整理的不够好,删略了部分内容DelphiCode: function GetVirtualMethodCount(AClass: TCla...
下面的方法获得virtual方法的数量,下面是高手的思想对话,整理的不够好,删略了部分内容
DelphiCode: 
function GetVirtualMethodCount(AClass: TClass): Integer;
var
  BeginVMT: Longint;
  EndVMT: Longint;
  TablePointer: Longint;
  I: Integer;
begin
  BeginVMT := Longint(AClass);
  {
  一个类的类型是指向类的指针,指针指向的内容是类的VMT,
  }
  EndVMT := PLongint(LongInt(AClass) + vmtClassName)^;
  {
  VMT到类的Field部分结束,通常Field的第一部分是类名
  所以VMT的终止地址是EndVmt
  }
  I := vmtSelfPtr + SizeOf(Pointer);
  repeat
    TablePointer := PLongint(Longint(AClass) + I)^;
    if (TablePointer <> 0) and (TablePointer >= BeginVMT) and
       (TablePointer < EndVMT) then
      EndVMT := Longint(TablePointer);
    Inc(I, SizeOf(Pointer));
  until I >= vmtClassName;

  Result := (EndVMT - BeginVMT) div SizeOf(Pointer);
end;
下面的方法获得某一个virtual方法的地址 DelphiCode:
function GetVirtualMethod(AClass: TClass;
  const Index: Integer): Pointer;
begin
  Result := PPointer(Integer(AClass) + Index * SizeOf(Pointer))^;
end;

以下面的类做测试
TTest = class
private
  procedure proc1;virtual;
public
  procedure proc2;virtual;
published
  procedure proc3;virtual;
  procedure proc4;virtual;
end;
以下是用于判断某个方法是不是虚方法的代码 DelphiCode:
var
  count,i:integer;
  p,fp:pointer;
begin
  fp:=@TTest.proc2;
  for i:=1 to getVirtualMethodCount(tone) do
    if getVirtualMethod(TTest,i)=fp then
      showmessage('ok');
end;
以上代码在Delphi 5下通过, 不知道有没有更好的方法, 通过字符串获得方法的地址,仅限于方法是在published部分 fp:=TTest.MethodAddress('proc3');//可以返回地址 fp:=TTest.MethodAddress('proc2');//返回nil 我还不会通过地址查找方法的名字,如果谁知道,告诉我吧,^_^ DelphiCode:
type
  TExample=class
   procedure dynamicMethod;dynamic;
   procedure virtualMethod;virtual;
   procedure abstractMethod;virtual; abstract;
  end;

procedure TForm1.Button2Click(Sender: TObject);
var
 e:TExample;
begin
  e:=TExample.Create;
  try
  try
  e.abstractMethod;
  except on EAbstractError do
  showmessage('sorry,this method is a abstract method.You should not call it directly');
  end;
  finally
  form1.Color :=clred;
  e.Free;
  end;
end;
你的方法是不能应用于Abstract的。 用异常的想法我有想到过。但我想要的是这样: if IsNotAbstract(aClass.aAbstractMethod) then aClass.aAbstractMethod; 而不是 try aClass.aAbstractMethod; except Error, this is a Abstract Method end;

上一页1234下一页

作者:网络 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号