手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>程序设计>delphi>列表

COM程序编写入门(二)

来源:互联网 作者:west263.com 时间:2008-02-23
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!
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方式的访问,而实现类的定义,是接口功能的实现。两者在功能和实现上都是有区别的。

上一篇: COM程序编写入门(三)
下一篇: 一个简单Tracer类,用来为应用写入跟踪

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!