4

我需要与一系列 .Net Web 服务进行交互。目前大约有150个。由于delphi 2010使用Thttprio来实现这一点,我试图在客户端创建一个通用代理,可以调用它来创建适当的soap服务客户端。有谁知道如何将 httprio 对象转换为通用接口类型?

谢谢

以下是我尝试使用的代理功能:

class function Web.Proxy<T>(svc: string): T;
var
  HTTPRIO : THTTPRIO;
begin
  HTTPRIO := THTTPRIO.Create(nil);
  HTTPRIO.URL := GetServiceURL(svc);
  Result:= HTTPRIO as T; //<-- Fails with "operator not applicable to this operand type"
  // Result:= T(HTTPRIO); //<-- also fails, but with "invalid typecast"
end;

这个想法是我可以这样称呼它:

Web.Proxy<AutmobileServiceSoap>('svc.asmx').GetAutomobile(125);

WSDL 导入的 AutomobileServiceSoap 定义如下:

AutmobileServiceSoap = interface(IInvokable)

所有 wsdl 导入都有一个函数,它以类似的方式返回 httprio 对象:

function GetAutomobileServiceSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): AutomobileServiceSoap;
const
  defWSDL = 'http://localhost:8732/Cars.Server/Data/AutomobileService.asmx?WSDL';
  defURL  = 'http://localhost:8732/Cars.Server/Data/AutomobileService.asmx';
  defSvc  = 'AutomobileService';
  defPrt  = 'AutomobileServiceSoap12';
var
  RIO: THTTPRIO;
begin
  Result := nil;
  if (Addr = '') then
  begin
    if UseWSDL then
      Addr := defWSDL
    else
      Addr := defURL;
  end;
  if HTTPRIO = nil then
    RIO := THTTPRIO.Create(nil)
  else
    RIO := HTTPRIO;
  try
    Result := (RIO as AutomobileServiceSoap);
    if UseWSDL then
    begin
      RIO.WSDLLocation := Addr;
      RIO.Service := defSvc;
      RIO.Port := defPrt;
    end else
      RIO.URL := Addr;
  finally
    if (Result = nil) and (HTTPRIO = nil) then
      RIO.Free;
  end;
end;
4

2 回答 2

5

您必须使用 RTTI 来获取接口的 GUID

type
  Web = class
    class function Proxy<T: IInterface>(svc: string): T;
  end;

class function Web.Proxy<T>(svc: string): T;
var
  HTTPRIO: THTTPRIO;
  data: PTypeData;
begin
  HTTPRIO := THTTPRIO.Create(nil);
  HTTPRIO.URL := GetServiceURL(svc);
  data := GetTypeData(TypeInfo(T));
  if ifHasGuid in data.IntfFlags then
  begin
    HTTPRIO.QueryInterface(data.Guid, Result);
  end;
end;

如果您指定 IInterface 约束,您可以确保 T 始终是一个接口(否则您还必须检查 TypeInfo 的 TypeKind)。

于 2013-07-02T14:36:46.233 回答
2

因为T可以是任何东西,你必须让 Delphi 清楚这T将是一个接口。由于所有接口都继承自IUnknown,因此您可以这样写:

  Web = class
    class function Proxy<T  :IUnknown>(svc : string) : T;
  end;
于 2013-07-02T14:26:19.930 回答