当前位置: 首页 > 图文教程 > 开发语言 > Delphi > Delphi学习:OOP 中的双刃剑

Delphi
文件管理(一)
文件管理(二)
文件管理(三)
剪贴板和动态数据交换(一)
剪贴板和动态数据交换(二)
对象链接与嵌入(一)
对象链接与嵌入(二)
Delphi拖放编程
动态链接库编程(一)
Delphi 应用编程实例简介
在Delphi应用程序中使用DLL
Delphi中API编程--在Delphi中调用API函数
如何在Delphi中制作“动态选单”
用Delphi编制金额大写转换程序
用Delphi制作Windows 98风格的工具栏
用Delphi检测特殊键状态
创建“控制面板”的新项目
用Delphi实现文件关联
Delphi使用三则
用Delphi制作“复活节彩蛋”

Delphi学习:OOP 中的双刃剑


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-30   浏览: 106 ::
收藏到网摘: n/a

 
前几天看一份非常有名的商业控件的源码,发现一个非常有趣的用法:


  Integer(xxx) := aaa;
 
  Tttt(xxx) := bbb;
 
  细细品味,发现利用这种用法往往可以收到意想不到的效果:
 
  比如:



 

  TTestRec = record
    A, B, C: Integer;
  end;
  TTestCls = class
  private
    FInner: TTestRec;
    FReadOnlyValue: Integer;
 
    function GetNewInner: PTestRec;
  public
    property Inner: TTestRec read FInner write FInner;
    property NewInner: PTestRec read GetNewInner;
    property ReadOnlyValue: Integer read FReadOnlyValue;
  end;
 
  你会发现,直接的你是改不了 aTestCls.Inner.A 的(编译时 delphi 直接报错,因为 delphi 7 中两个 recode 赋值是 copy memory 而不是简单的“传址”!
 

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TTestCls.Create do
  try
//    Inner.A := 10;
    Caption := TButton(Sender).Caption + ' A := ' + IntToStr(Inner.A);
  finally
    Free;
  end;
end;
 
  可是,如果我们知道在访问这个 Inner 时 delphi 在编译直接 FInner 的地址,那么,结合上面那种有趣的用法:
 

procedure TForm1.Button3Click(Sender: TObject);
var
  p: PInteger;
begin
  with TTestCls.Create do
  try
    p := @(Inner.A);
    Integer(p^) := 100;
    Caption := TButton(Sender).Caption + ' A := ' + IntToStr(Inner.A);
  finally
    Free;
  end;
end;
  更进一步,利用指针竟然可以突破 oo 对 private 的保护:

procedure TForm1.Button4Click(Sender: TObject);
var
  p: PInteger;
begin
  with TTestCls.Create do
  try
    p := @