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

Delphi
Delphi设计简易对象垃圾回收框架
Delphi开发Web应用程序打印组件
Delphi客户服务器应用开发(四)
Delphi自定义部件开发(一)
Delphi自定义部件开发(二)
Delphi自定义部件开发(三)
Delphi自定义部件开发(四)
开发Delphi对象式数据管理功能(一)
开发Delphi对象式数据管理功能(二)
开发Delphi对象式数据管理功能(三)
开发Delphi对象式数据管理功能(四)
开发Delphi对象式数据管理功能(五)
用Delphi语言来学设计模式之简单工厂篇
Delphi2005和DUnit搭建敏捷开发平台记录
你想成Delphi高手吗?快来学Delphi快捷键
Borland最新版开发工具Delphi2005抢先预览
用Delphi实现JPEG格式图像的显示
用DELPHI编程访问SQL SERVER数据库
用Delphi编制趣味动画鼠标
用Delphi实现选单的自动隐藏功能

Delphi学习:OOP 中的双刃剑


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