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

标签 delphi generics interface delphi-xe7

我编写了一个函数,它接受类类型 (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/

相关文章:

algorithm - 如何在 Delphi 中实现决策矩阵

database - 使用 Delphi 的客户端/服务器应用程序(多用户)的最佳数据库选择?

delphi - 如何将一些项目添加到 Delphi IDE 的代码完成组合框中

java - 使用通用 Comparable<T> 数据在 Java 中实现二叉树?

Java接口(interface)成员

delphi - 是否可以在 Delphi 中为通用记录创建类型别名

swift - 是否可以向 Swift 协议(protocol)一致性扩展添加类型约束?

java - 在通配符类型 ArrayList 中添加元素

java - 在接口(interface)中使用默认方法是否违反了接口(interface)隔离原则?

Java——界面设计