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

Delphi
Delphi 4.0 制作数据库发行盘技巧
用Delphi 开发数据库程序经验三则
在Delphi中定位文件位置
Delphi编程技巧实例
delphi构件制作方法简介
在Delphi中如何控制其它应用程序窗口
用Delphi实现远程屏幕抓取
用Delphi6制作网页特效软件
Delphi多层应用程序的实现
Delphi下汉字输入法的编程及使用
Delphi巧克力的滋味(1)
DELPHI下汉字输入法的编程及使用(1)
Delphi中高级DLL的编写和调用(1)
Delphi中实现多线程同步查询(1)
Delphi中实现多线程同步查询(2)
Delphi中对Oracle存取RTF文档(1)
Delphi5实现多层Client/Server应用程序(1)
扩展Delphi的线程同步对象(1)
Delphi制作带图标的弹出式选单
用Delphi编写安装程序(1)

Delphi学习:OOP 中的双刃剑


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-30   浏览: 103 ::
收藏到网摘: 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 := @