【问题标题】:How to obtain GUID of interface passed as a generic parameter in Delphi?如何获取在Delphi中作为通用参数传递的接口的GUID?
【发布时间】:2021-04-17 04:56:06
【问题描述】:

在下文中,Obtain() 方法有效,但 GetAs() 方法对调用者来说会更整洁。

但是,我不知道如何将接口作为通用参数传递并获取其 GUID。

声明:

  TInterfaceRegistry = class
  private
    fRegistry: TDictionary<TGUID, IInterface>;
  public
    ...
    procedure Register(const IID: TGUID; IntfObj: IInterface; const Replace: Boolean = False);
    function  Obtain(const IID: TGUID; out IntfObj): Boolean;
    function  GetAs<I: IInterface>(): I;
  end;

实施:

function TInterfaceRegistry.Obtain(const IID: TGUID; out IntfObj): Boolean;
var
  Found: IInterface;
begin
  Result  := fRegistry.TryGetValue(IID, Found);
  if  Result  then
    if  not Supports(Found, IID, IntfObj) then
      raise EBatSoft.Create(SEBatSoftBug);
end;

function  TInterfaceRegistry.GetAs<I>(): I;
begin
  if  not Obtain(I, Result) then
    raise EBatSoft.Create(SEDoesNotImplement);
end;

调用它看起来像这样......

  IntfReg.Register(IMyIntf, TMyImpl.Create);

获得实施:

var
  Intf: IMyIntf;
begin
  // Less type-safe (can pass anything into 2nd parameter)
  if IntfReg.Obtain(IMyIntf, Intf)  then
    ...
  // Fully type-safe, and simple
  Intf := IntfReg.GetAs<IMyIntf>();

【问题讨论】:

    标签: delphi generics interface


    【解决方案1】:

    你必须通过GetTypeData(TypeInfo(I)).GUID使用typeinfo。

    请记住,如果您没有为正在使用的给定接口声明任何 guid,而非泛型方法根本无法编译,这可能会返回一个空的 guid。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 2017-05-29
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多