·天新网首页·加入收藏·设为首页
首页|笔记本|手机|数码相机|摄像机|MP3/MP4|主板|内存|显示器|办公|打印机|下载|开发|汽车|学院|业界
硬件|台式机|数码|数字家庭|投影仪|GPS/CPU|显卡|硬盘|服务器|网络|一体机|驱动|源码|游戏|考试|报价
COM程序编写入门(二)
http://dev.21tx.com 2005年03月14日

COM的理论
以实例来讲
COM的接口(Interface)是COM的核心,所有的COM接口都是通过IUnknown派生出来的,它告知客户那些接口是有效的,即已经被实现类说定义。它定义的一般方式如下:

ISimpleInterface=Interface(IUnknown)

Function GetName:String

Procedure SetName(v_Name:String)

End;

如果在上面的接口中加入这样一行:

ISimpleInterface=Interface(IUnknown)

V_Name:String;

Function GetName:String

Procedure SetName(v_Name:String)

End;

这样是不被允许的,因为上面我们说到接口方法就像是一个占位符,需要实现类引出才有实际意义,v_Name:String这一句只是一个数据成员将永远无任何意义,如果要定义也只能在实现类中定义。

现在举一个COM的例子,没有什么实际用处但至少说明问题:

unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls;

type

TForm1 = class(TForm)

Label1: TLabel;

Edit1: TEdit;

Button1: TButton;

Button2: TButton;

procedure FormCreate(Sender: TObject);

procedure Button1Click(Sender: TObject);

procedure Button2Click(Sender: TObject);

procedure FormClose(Sender: TObject; var Action: TCloseAction);

private

{ Private declarations }

public

{ Public declarations }

end;

ISimpleInterface=Interface(IUnknown)

Procedure SetValue(v_Value:Integer);

Function GetValue:Integer;

End;

TSimpleImple=Class(TInterfacedObject,ISimpleInterface)

Public

Value:Integer;

Procedure SetValue(v_Value:Integer);

Function GetValue:Integer;

End;

var

Form1: TForm1;

v_Obj:TSimpleImple;

implementation

{$R *.dfm}

{ TSimpleImple }

function TSimpleImple.GetValue: Integer;

begin

Result:=Value;

end;

procedure TSimpleImple.SetValue(v_Value: Integer);

begin

Value:=v_Value;

end;

procedure TForm1.FormCreate(Sender: TObject);

begin

v_Obj:=TSimpleImple.Create;

end;

procedure TForm1.Button1Click(Sender: TObject);

begin

v_Obj.SetValue(StrToInt(Edit1.Text));

Edit1.Clear;

end;

procedure TForm1.Button2Click(Sender: TObject);

begin

Edit1.Text:=IntToStr(v_Obj.GetValue);

end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);

begin

v_Obj.Free;

end;

end.

蓝色字样即定义了一个接口,在形式上在ISimpleInterface(接口定义)和TSimpleImple(实现类)几乎定义都差不多,但是我要强调的是,接口定义是为了实现OLE方式的访问,而实现类的定义,是接口功能的实现。两者在功能和实现上都是有区别的。

上一篇: 在DELPHI7中不使用任何第三方控件,实现放在工具栏上可拖动的XP风格菜单
下一篇: COM程序编写入门(三)

Google
 
热点文章
关于我们 | 联系我们 | 广告服务 | 工作机会 | 版权声明 | 欢迎投稿 | 网站地图
Copyright © 2000-2008 , www.21tx.com , All Rights Reserved .
晨新科技 版权所有 Created by TXSite.net