Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Delphi中获取作为泛型参数传递的接口的GUID?_Delphi_Generics_Interface - Fatal编程技术网

如何在Delphi中获取作为泛型参数传递的接口的GUID?

如何在Delphi中获取作为泛型参数传递的接口的GUID?,delphi,generics,interface,Delphi,Generics,Interface,在下面的示例中,方法get()可以工作,但是GetAs()方法对于调用方来说更整洁 但是,我不知道如何将接口作为泛型参数传递并获取其GUID 声明: TInterfaceRegistry = class private fRegistry: TDictionary<TGUID, IInterface>; public ... procedure Register(const IID: TGUID; IntfObj: IInterface; cons

在下面的示例中,方法get()可以工作,但是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;
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>();
var
Intf:IMyIntf;
开始
//类型安全性较低(可以将任何内容传递到第二个参数)
如果IntfReg.acquire(IMyIntf,Intf),那么
...
//完全类型安全,简单
Intf:=IntfReg.GetAs();

您必须通过
GetTypeData(typeinfo(I)).GUID使用typeinfo


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

您必须通过
GetTypeData(typeinfo(I)).guid使用typeinfo


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

谢谢!太好了非常感谢。太好了
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>();