class function TObject.ClassName: ShortString;
{$IFDEF PUREPASCAL}
begin
Result := PShortString(PPointer(Integer(Self) + vmtClassName)^)^;
end;这是Delphi源码
但是我把这个代码写在一个按钮中, 怎么就是报内存错误呢procedure TForm1.Button1Click(Sender: TObject);begin
ShowMessage(PShortString(PPointer(Integer(Self) + vmtClassName)^)^);
end;
{$IFDEF PUREPASCAL}
begin
Result := PShortString(PPointer(Integer(Self) + vmtClassName)^)^;
end;这是Delphi源码
但是我把这个代码写在一个按钮中, 怎么就是报内存错误呢procedure TForm1.Button1Click(Sender: TObject);begin
ShowMessage(PShortString(PPointer(Integer(Self) + vmtClassName)^)^);
end;
这一条语句,可能是由编译器作了特殊处理的,在普通的类实例方法中调用此语句,可能就要出现内存访问错误。这只是猜测。ShowMessage(ClassName)这样不行吗?
在一个类方法中, Self代表类本身procedure TForm1.Button1Click(Sender: TObject);begin
ShowMessage(PShortString(PPointer(Integer(PPointer(Self)^) + vmtClassName)^)^);
end;
类中self指针指向vmt,对象中self指向对象的数据空间,而对象数据空间的前4字节保存指向vmt的指针,所以类中的Integer(Self)正好等于对象中的PInteger(Self)^
而self在类方法中代表了类本身。 3,4楼说的正确。