gpt4 book ai didi

delphi - 使用泛型创建接口(interface)对象

转载 作者:行者123 更新时间:2023-12-03 14:46:24 25 4
gpt4 key购买 nike

我编写了一个函数,它接受类类型 (T) 和接口(interface)类型 (I),并向对象 (T) 返回接口(interface) (I)。这是代码。

interface

function CreateObjectInterface<T: Class, constructor; I: IInterface>(
out AObject: TObject): I;

...

implementation

function TORM.CreateObjectInterface<T, I>(out AObject: TObject): I;
begin
AObject := T.Create;

if not Supports(AObject, GetTypeData(TypeInfo(I))^.Guid, Result) then
begin
AObject.Free;
AObject := nil;

raise EORMUnsupportedInterface.CreateFmt(
'Object class "%s" does not support interface "%s"',
[AObject.ClassName, GUIDToString(GetTypeData(TypeInfo(I))^.GUID)]
);
end;
end;

该函数按预期工作,没有内存泄漏或其他不良情况。

还有其他方法可以达到相同的结果吗?

最佳答案

这段代码有一个错误。如果您的对象实例支持 IUnknown 但不支持您要求的接口(interface),则支持将销毁您的对象实例。

简单演示:

type
IFoo = interface
['{32D3BE83-61A0-4227-BA48-2376C29F5F54}']
end;

var
o: TObject;
i: IFoo;
begin
i := TORM.CreateObjectInterface<TInterfacedObject, IFoo>(o); // <- boom, invalid pointer
end.

最好将 IInterfaceIUnknown 作为 T 的附加约束。

或者确保您没有销毁已经销毁的实例。

除非您想支持动态 QueryInterface 实现(其中类不实现接口(interface),但 QueryInterface 返回它),否则我会选择 Supports 调用类:

function TORM.CreateObjectInterface<T, I>(out AObject: TObject): I;
begin
if not Supports(TClass(T), GetTypeData(TypeInfo(I))^.Guid) then
raise EORMUnsupportedInterface.CreateFmt(
'Object class "%s" does not support interface "%s"',
[AObject.ClassName, GUIDToString(GetTypeData(TypeInfo(I))^.GUID)]
);

AObject := T.Create;
Supports(AObject, GetTypeData(TypeInfo(I))^.Guid, Result);
end;

关于delphi - 使用泛型创建接口(interface)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29118950/

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