本文介绍了无法将类型(Null)的变体转换为类型(OleStr)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道为什么下面的代码块会否定某些计算机上的无法将类型(Null)的变体转换为类型(OleStr)",不是所有的计算机,而是十分之三的计算机都会生成错误消息.

Do you know why the block of code bellow will negate the "Could not convert variant of type (Null) into type (OleStr)" on some computers, not all of them but 3 out of ten computers generate the error message.

function GetWMIstringSW(const WMIClass, WMIProperty:string): string;

const
  wbemFlagForwardOnly = $00000020;

var
  FWbemObjectSet: OLEVariant;
  FWbemObject   : OLEVariant;
  oEnum         : IEnumvariant;
  iValue        : LongWord;
  LNode         : TTreeNode;
  LNode2        : TTreeNode;

begin
  Result:='';
  FWbemObjectSet:= FWMIService.ExecQuery(Format('Select %s from %s',[WMIProperty, WMIClass]),'WQL',wbemFlagForwardOnly);
  oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;

  while oEnum.Next(1, FWbemObject, iValue) = 0 do
    begin
      if not VarIsNull(FWbemObject.Properties_.Item(WMIProperty).Value) then
      Result:=FWbemObject.Properties_.Item(WMIProperty).Value;
      LNode := ClientForm.TreeView1.Items.AddChild(Node, Format('%s',[String(FWbemObject.Name)]));

      LNode2 := ClientForm.TreeView1.Items.AddChild(LNode, Format('%s',[String(FWbemObject.Version)]));
      FWbemObject:=Unassigned;
    end;

end;

然后在FormCreate上执行该函数:

The function is then executed at FormCreate:

GETWMIstringSW('Win32_Product','Name');

非常感谢您的帮助.

推荐答案

当WMI属性的值返回null时,您的代码将失败.您可以解决此问题,在转换或转换为字符串之前检查属性是否具有null值.对于此任务,您可以使用 VarIsNull 函数或仅使用 VarToStr 方法可将变体安全地转换为类似的字符串.

You code fails when the value of a WMI property returns null. You can fix this, checking if the property has a null value before to cast or convert to an string. For this task you can use the VarIsNull function or just use the VarToStr method to safely convert variants to strings like so.

 LNode := ClientForm.TreeView1.Items.AddChild(Node,
              Format('%s',[VarToStr(FWbemObject.Name)]));
 LNode2 := ClientForm.TreeView1.Items.AddChild(LNode,
              Format('%s',[VarToStr(FWbemObject.Version)]));

这篇关于无法将类型(Null)的变体转换为类型(OleStr)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 23:14