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

Delphi
Delphi客户服务器应用开发(三)
Delphi快速入门(五)
Delphi面向对象的编程方法(一)
Delphi面向对象的编程方法(二)
Delphi面向对象的编程方法(三)
Delphi面向对象的编程方法(四)
字符串列表及应用(一)
字符串列表及应用(二)
文本编辑器的设计(一)
文本编辑器的设计(二)
Delphi图形图像编程(一)
Delphi的两个实用技巧(1)
Delphi的两个实用技巧(2)
delphi实例编程之--制作可随处拖放的工具栏
Delphi快速入门(一)
Delphi快速入门(二)
Delphi快速入门(三)
Delphi快速入门(四)
动态链接库编程(二)
Delphi图形图像编程(二)

Delphi学习:OOP 中的双刃剑


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