Delphi

本类阅读TOP10

·分布式网络考试系统原型分析及实现
·游戏外挂设计技术探讨①
·使用HOOK随心监视Windows
·Delphi 水晶报表打包解决
·试题库开发中非文本数据的处理
·如何将几个DBGRID里的内容导入同一个EXCEL表中....的问题
·如何使用Delphi设计强大的服务器程序
·工人线程中关闭窗体的实现
·用DLL方式封装MDI子窗体。
·支持XP下托盘栏气球提示的托盘单元

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
COM程序编写入门(全文-2)

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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方式的访问,而实现类的定义,是接口功能的实现。两者在功能和实现上都是有区别的。

 

(待续…)




相关文章

相关软件