如何在VCL类中使用接口-第2部分 [英] How to use Interface with VCL Classes - Part 2
问题描述
继续我之前有关将接口与VCL一起使用的调查。
continue with my previous investigation regarding the use of Interface with VCL.
< a href = https://stackoverflow.com/questions/8805768/how-to-use-interface-with-vcl-classes>如何在VCL类中使用接口?
我想举一个代码示例来演示两者在哪里以及如何一起工作。
或两者的经典收益/用法是什么?
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;
推荐答案
假设您有 TSomeThing
和 TSomeThingElse
类,但是它们没有共同的祖先类。照原样,您将无法将它们传递给相同的函数,也无法对其调用通用方法。通过将共享接口添加到两个类,您可以同时执行这两个操作,例如:
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;
这篇关于如何在VCL类中使用接口-第2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!