问题
continue with my previous investigation regarding the use of Interface with VCL.
How to implement identical methods with 2 and more Classes?
How to use Interface with VCL Classes?
I would like to have a code example to demonstrate where and how the two work together. Or what is the classic benefit/usage of the two:
ISomething = interface
['{EFE0308B-A85D-4DF3-889C-40FBC8FE84D0}']
...
end;
TSomeThing = class(TSomeVCLObject, ISomething)
...
end;
回答1:
Imagine you have TSomeThing
and TSomeThingElse
classes, but they do not have a common ancestor class. As-is, you would not be able to pass them to the same function, or call a common method on them. By adding a shared interface to both classes, you can do both, eg:
type
ISomething = interface
['{EFE0308B-A85D-4DF3-889C-40FBC8FE84D0}']
public
procedure DoSomething;
end;
TSomeThing = class(TSomeVCLObject, ISomething)
...
procedure DoSomething;
end;
TSomeThingElse = class(TSomeOtherVCLObject, ISomething)
...
procedure DoSomething;
end;
procedure TSomeThing.DoSomething;
begin
...
end;
procedure TSomeThingElse.DoSomething;
begin
...
end;
procedure DoSomething(Intf: ISomething);
begin
Intf.DoSomething;
end;
procedure Test;
var
O1: TSomeThing;
O2: TSomeThingElse;
Intf: ISomething;
begin
O1 := TSomeThing.Create(nil);
O2 := TSomeThingElse.Create(nil);
...
if Supports(O1, ISomething, Intf) then
begin
Intf.DoSomething;
DoSomething(Intf);
end;
if Supports(O2, ISomething, Intf) then
begin
Intf.DoSomething;
DoSomething(Intf);
end;
...
O1.Free;
O2.Free;
end;
来源:https://stackoverflow.com/questions/8810052/how-to-use-interface-with-vcl-classes-part-2