如何将对象转换为Delphi中泛型类型约束的接口

如何将对象转换为Delphi中泛型类型约束的接口,第1张

概述我需要与一系列.Net Web服务进行交互.目前大约有150个. 由于delphi 2010使用Thttprio来实现这一点,我试图在客户端创建一个通用代理,可以调用它来创建适当的soap服务客户端. 有谁知道如何将httprio对象转换为通用接口类型? 谢谢 下面是我正在尝试使用的代理函数: class function Web.Proxy<T>(svc: string): T;var H 我需要与一系列.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导入的AutmobileServiceSoap定义如下:

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;
解决方法 您必须使用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).

总结

以上是内存溢出为你收集整理的如何将对象转换为Delphi中泛型类型约束的接口全部内容,希望文章能够帮你解决如何将对象转换为Delphi中泛型类型约束的接口所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1248796.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存