gpt4 book ai didi

class - 如何在 Object Pascal "class of interface"(或 "interface of interface")类型中创建

转载 作者:行者123 更新时间:2023-12-03 19:22:13 24 4
gpt4 key购买 nike

看看这个示例:

//----------------------------------------------------------------------------
type

ISomeInterface = interface
procedure SomeMethod;
end;

// this is wrong, but illustrates that, what i need:
TSomeClassWhichImplementsSomeInterface = class of ISomeInterface;

var
gHardCodedPointer: Pointer; // no matter

procedure Dummy(ASomeClassToWorkWith: TSomeClassWhichImplementsSomeInterface);
begin
// actually, type of ASomeClassToWorkWith is unknown (at least TObject), but it
// must implement SomeMethod, so i can make something like this:
ASomeClassToWorkWith(gHardCodedPointer).SomeMethod;
end;

...

type

TMyClass = class(TInterfacedObject, ISomeInterface)
end;

...

// TMyClass implements ISomeInterface, so i can pass it into Dummy:
Dummy(TMyClass);
//----------------------------------------------------------------------------

当然,我可以继承 TMyClass 并使用它的子类,但我不需要这个。我想使用具有自己的层次结构的其他类,只需添加 ISomeInterface 的实现(因为在 Object Pascal 中没有可用的多重继承,就像在 C++ 中一样)。我知道这可能看起来很疯狂,不要问我为什么需要这个,只是说 - 它可能会实现或不会。非常感谢!

最佳答案

我认为您正在寻找的是:

procedure Dummy; 
var Intf : ISomeInterface;
begin
if Assigned(gHardCodedPointer) and Supports(gHardCodedPointer,ISomeInterface,Intf) then
Intf.SomeMethod
end;

如果不是,我不知道你想在那里实现什么......

关于class - 如何在 Object Pascal "class of interface"(或 "interface of interface")类型中创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3499787/

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