Delphi中自定义类和接口

Delphi中自定义类和接口

1.自定义类,例子如下:

......

type

TMyObject = class
private
  FValue : Integer;
  procedure SetValue(AValue : Integer);

published

//定义属性 ,访问 Value时 ,取 FValue的值 ,如果赋值给Value ,则调用SetValue方法
  property Value : Integer read FValue  write SetValue; 

end;

 

implementation

 

procedure TMyObject.SetValue(AValue : Integer);
begin
   FValue:= AValue;
end;

 

procedure TForm1.Button1Click(Sender: TObject);
var
  obj : TMyObject;
begin
  obj := TMyObject.Create;
  obj.Value := 123; //调用 SetValue(123) ;
  ShowMessage(IntToStr(obj.Value));  //123
end;

......

 

2.接口

定义接口如下:

type
  IFoo = interface
    ['{4A8BFAB3-E565-4AC0-97B4-D166B46D4B6F}']
    function F1 : Integer;
  end;

  IBar = interface(IFoo)
    ['{E6A7FBD6-68E7-43E7-B2E9-717FE9A4115B}']
    function F2 : Integer;
  end;

 

 

定义实现类:

type
  TFooBar = class(TInterfacedObject, IFoo, IBar)
    function F1 : Integer;
    function F2 : Integer;
  end;

 

implementation
{$R *.dfm}

 

function TFooBar.F1 : Integer;
begin
  Result := 1;
end;

 

function TFooBar.F2 : Integer;
begin
  Result := 2;
end;

 

注意:

如果一个类实现多个接口,但恰好这些接口有同名的方法时,我们需要给同名的方法取别名,例如:

type
  IFoo = interface
    ['{4A8BFAB3-E565-4AC0-97B4-D166B46D4B6F}']
    function F1 : Integer;
  end;

  IBar = interface(IFoo)
    ['{E6A7FBD6-68E7-43E7-B2E9-717FE9A4115B}']
    function F1 : Integer;
  end;

type
  TFooBar = class(TInterfacedObject, IFoo, IBar)
    //aliased methoeds
    function IFoo.F1 = F1;
    function IBar.F1 = F2;
    //interface methoeds
    function F1 : Integer;
    function F2 : Integer;
  end;

implementation
{$R *.dfm}

function TFooBar.F1 : Integer;
begin
  Result := 1;
end;

function TFooBar.F2 : Integer;
begin
  Result := 2;
end;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值