我一直认为OleVariant变量的初始值总是等于Unassigned(类型VT_EMPTY).但是下面用XE3编译的简单代码告诉我这不是真的.
{$APPTYPE CONSOLE}
uses
  ActiveX;
function GetValue: OleVariant;
begin
  Result := TVariantArg(Result).vt;
end;
function GetValue2: OleVariant;
begin
  Result := 10;
  Result := GetValue;
end;
var
  Msg: string;
begin
  Msg := GetValue2;
  Writeln(Msg);
end.
App写"3".这是正常的吗?
对于不适合寄存器的类型,Delphi函数的返回值作为var参数传递.所以编译器将代码转换成如下:
procedure GetValue(var Result: OleVariant);
因此,Result函数入口的值是您为其分配返回值的变量的值.
所以你的调用代码转换为
function GetValue2: OleVariant;
begin
  Result := 10;
  GetValue(Result);
end;
所以整个程序就变成了
{$APPTYPE CONSOLE}
uses
  ActiveX;
procedure GetValue(var Result: OleVariant);
begin
  Result := TVariantArg(Result).vt;
end;
procedure GetValue2(var Result: OleVariant);
begin
  Result := 10;
  GetValue(Result);
end;
var
  tmp: OleVariant;
  Msg: string;
begin
  GetValue2(tmp);
  Msg := tmp;
  Writeln(Msg);
end.
这解释了输出VT_I4.
当然,这完全是实施细节的结果.您应该始终初始化函数返回值.