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

Delphi
利用Delphi编写Socket通信程序
用Delphi设计“抢三十”游戏
对《QQ列表精灵》源代码分析和仿制
Delphi接口编程的两大陷阱
基于Delphi的组件设计之简单实例
基于Delphi的组件设计之概念
浅述Delphi下的OpenGL图形开发
深入理解Delphi的消息机制
Delphi处理SQL Server多媒体数据
Delphi中为RichEdit加入链接
用Delphi7设计FTP上传软件
利用Delphi编程控制摄像头
用Delphi实现快闪窗体信息提示
Delphi制作图形化的ComboBox
用Delphi设计能携带附件的EMail
Delphi中利用网页打造程序界面
Delphi控件的“拿来主义”
Delphi设计PhotoShop型弹出菜单
用Delphi获取Windows及系统路径
Delphi控制Excel自动生成报表

Delphi学习:OOP 中的双刃剑


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