加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 如何测试OleVariant是否包含接口

发布时间:2020-12-15 09:07:17 所属栏目:大数据 来源:网络整理
导读:通过其自动化界面使用Excel的一个令人烦恼的事情是弱类型. 返回值可以包含任何不同类型. 如何测试调用者返回的变量是否为ExcelRange接口? function TAddInModule.InBank: boolean;var ExcelAppAsVariant: OleVariant; test: string; Caller: OleVariant;beg
通过其自动化界面使用Excel的一个令人烦恼的事情是弱类型.
返回值可以包含任何不同类型.
如何测试调用者返回的变量是否为ExcelRange接口?

function TAddInModule.InBank: boolean;
var
  ExcelAppAsVariant: OleVariant;
  test: string;
  Caller: OleVariant;
begin  //Exception handling omitted for brevity. 
  Result:= false;
  ExcelAppAsVariant:= ExcelApp.Application;
  Caller:= ExcelApp.Application.Caller[EmptyParam,0];
  if IDispatch(Caller) is ExcelRange then begin //E2015 Operator not applicable 
    Result:= lowercase(Caller.Parent.Name) = 'bank' 
  end;
end;

(讽刺的是as运算符的工作原理(IDispatch(Caller)作为ExcelRange).Parent;编译得很好).

以下代码有效,但似乎过于冗长:

if VarIsType(Caller,varDispatch) then begin 
  IUnknown(Caller).QueryInterface(ExcelRange,ICaller) 
  if Assigned(ICaller) then ICaller......

还没有内置函数VarIsInterface(Variant,Interface).
如何测试OleVariant是否包含给定的接口?

另见:How to cast OleVariant to IDispatch derived?

编辑
谢谢大家,我使用以下方法进行测试,因为Excel将接口和OleStrings混合为可能的返回值.

if VarIsType(Caller,varDispatch) and Supports(Caller,ExcelRange) then begin

解决方法

我可能会使用 Supports

if Supports(Caller,ExcelRange) then
  ....

这解析为@Stijn给出的相同代码,但Supports调用更简洁.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读