如何在Delphi中创建OleVariant兼容类?

时间:2010-02-05 14:59:01

标签: delphi

Delphi 2006. XML数据绑定。 生成这个类:


type
  IXMLItem = interface(IXMLNode)  
    ['{10B9A877-A975-4FC7-B9EF-448197FA1B90}']  
    { Property Accessors }
    function Get_PartNum: TPartNum_Sku;
    procedure Set_PartNum(Value: TPartNum_Sku);
    { Methods & Properties }
    property PartNum: TPartNum_Sku read Get_PartNum write Set_PartNum;
  end;

  { TXMLItem }

  TXMLItem = class(TXMLNode, IXMLItem)
  protected
    { IXMLItem }
    function Get_PartNum: TPartNum_Sku;
    procedure Set_PartNum(Value: TPartNum_Sku);
  end;
...
function TXMLItem.Get_PartNum: TPartNum_Sku;
begin
  Result := AttributeNodes['partNum'].NodeValue;
end;

procedure TXMLItem.Set_PartNum(Value: TPartNum_Sku);
begin
  SetAttribute('partNum', Value);
end;

How to create OleVariant compatible class TPartNum_Sku? So what would the code:

Result := AttributeNodes['partNum'].NodeValue;

translated without error

Result := AttributeNodes['partNum'].NodeValue;

1 个答案:

答案 0 :(得分:1)

您正在读取XML属性的值,并且您尝试将其分配给TPartNum_Sku类型的某些内容。属性值的编译时类型为OleVariant,但由于XML属性始终为字符串,因此OleVariant中存储的值的运行时类型始终为WideString。它永远不会保存TPartNum_Sku类型的值,因此您定义该类与OleVariant兼容的目标是错误的,因为它们不需要兼容。 (只是因为这就是编译器所说的问题并不意味着你需要修复它。编译器有时会说“预期分号”,但它很少意味着你应该在那里添加分号。)

拥有Get_PartNum函数的重点是,您可以字符串属性值转换为TPartNum_Sku对象。如果TPartNum_Sku是一个类,则可以调用其构造函数:

Result := TPartNum_Sku.Create(AttributeNodes['partNum'].NodeValue);

请注意,当您这样做时,Get_PartNum调用者负责释放该对象。

如果您的类型是枚举,则转换取决于属性值。如果它是枚举的数值,那么你可以使用它:

Result := TPartNum_Sku(StrToInt(AttributeNodes['partNum'].NodeValue));

如果是字符串名称,那么你可以试试这个:

Result := TPartNum_Sku(GetEnumValue(TypeInfo(TPartNum_Sku),
                                    AttributeNodes['partNum'].NodeValue);

GetEnumValue位于 TypInfo 单元中。您也可以从 Classes 单元尝试IdentToInt

您还必须为Set_PartNum函数编写反向代码。