Delphi 系统[27]关键字和保留字 implements

Delphi 系统[27]关键字和保留字  implements

1、定义:

  • implements :指出了一个属性从接口继承,此时属性被转换成接口对象。通过接口动态绑定属性,并动态的设定属性值。

2、示例及说明:

implements 指令允许您将接口的实现委托给实现类中的属性。例如:

property MyInterface: IMyInterface read FMyInterface implements IMyInterface;

声明一个名为MyInterface的属性,该属性实现接口IMyInterface。

implements指令必须是属性声明中的最后一个说明符,并且可以列出多个接口,用逗号分隔。委托属性逗号分隔。委托属性:

  • 必须是类或接口类型。
  • 不能是数组属性或具有索引说明符。
  • 必须具有读取说明符。如果属性使用读取方法,则该方法必须使用默认的寄存器调用约定,并且不能是动态的(尽管可以是虚拟的)或指定消息指令。

注:用于实现委托接口的类应派生自 TAggregatedObject。

2.1 类-类型属性

如果委托属性属于类类型,则在搜索封闭类及其祖先之前,将搜索该类及其祖先以查找实现指定接口的方法。因此,可以在属性指定的类中实现一些方法,在声明属性的类中实现其他方法。方法解析子句可以用通常的方式来解析歧义或指定特定的方法。接口不能由多个类类型属性实现。例如:

type
  IMyInterface = interface
    procedure P1;
    procedure P2;
  end;
  TMyImplClass = class
    procedure P1;
    procedure P2;
  end;
  TMyClass = class(TInterfacedObject, IMyInterface)
    FMyImplClass: TMyImplClass;
    property MyImplClass: TMyImplClass read FMyImplClass implements IMyInterface;
    procedure IMyInterface.P1 = MyP1;
    procedure MyP1;

  end;
procedure TMyImplClass.P1;
  ...
procedure TMyImplClass.P2;
  ...
procedure TMyClass.MyP1;
  ...
var
  MyClass: TMyClass;
  MyInterface: IMyInterface;
begin
  MyClass := TMyClass.Create;
  MyClass.FMyImplClass := TMyImplClass.Create;
  MyInterface := MyClass;
  MyInterface.P1;        // calls TMyClass.MyP1;
  MyInterface.P2;        // calls TImplClass.P2;
end;

2.2 接口-类型属性

如果委托属性属于接口类型,则该接口或其派生的接口必须出现在声明该属性的类的祖先列表中。委托属性必须返回一个对象,该对象的类完全实现implements指令指定的接口,并且该对象不使用方法解析子句。例如:  

type
  IMyInterface = interface
    procedure P1;
    procedure P2;
  end;
  TMyClass = class(TObject, IMyInterface)
    FMyInterface: IMyInterface;
    property MyInterface: IMyInterface read FMyInterface implements IMyInterface;
  end;
var
  MyClass: TMyClass;
  MyInterface: IMyInterface;
begin
  MyClass := TMyClass.Create;
  MyClass.FMyInterface := ...  // 类实现IMyInterface的某个对象

  MyInterface := MyClass;
  MyInterface.P1;
end;

  

  

 

 

 

 

创建时间:2021.08.16  更新时间:

posted on 2021-08-16 15:27  滔Roy  阅读(183)  评论(0编辑  收藏  举报

导航