gpt4 book ai didi

delphi - Delphi中的接口(interface)多态性

转载 作者:行者123 更新时间:2023-12-03 15:43:26 25 4
gpt4 key购买 nike

我有两个接口(interface),一个派生自另一个接口(interface):

type
ISomeInterface = interface
['{5A46CC3C-353A-495A-BA89-48646C4E5A75}']
end;

ISomeInterfaceChild = interface(ISomeInterface)
['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}']
end;

现在我有一个参数为 ISomeInterface 的程序,如下所示:

procedure DoSomething(SomeInterface: ISomeInterface);

我想检查 SomeInterface 是否为 ISomeInterfaceChild。 Delphi 7 中的接口(interface)不支持 Is 运算符,我也不能在此处使用 Supports。我能做什么?

最佳答案

您确实可以使用支持。您所需要的只是:

Supports(SomeInterface, ISomeInterfaceChild)

该程序说明:

program SupportsDemo;

{$APPTYPE CONSOLE}

uses
SysUtils;

type
ISomeInterface = interface
['{5A46CC3C-353A-495A-BA89-48646C4E5A75}']
end;

ISomeInterfaceChild = interface(ISomeInterface)
['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}']
end;

procedure Test(Intf: ISomeInterface);
begin
Writeln(BoolToStr(Supports(Intf, ISomeInterfaceChild), True));
end;

type
TSomeInterfaceImpl = class(TInterfacedObject, ISomeInterface);
TSomeInterfaceChildImpl = class(TInterfacedObject, ISomeInterface, ISomeInterfaceChild);

begin
Test(TSomeInterfaceImpl.Create);
Test(TSomeInterfaceChildImpl.Create);
Readln;
end.

输出

FalseTrue

关于delphi - Delphi中的接口(interface)多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16686345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com