开发者

Assign value to variant parameter

I got code like this in Delphi XE

function DoSomething(MyVar : Variant) : boolean;
begin
  MyVar := 'Bar';
  Result := true;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  foo : string;
begin
  foo := '';
  showmessage(foo); // shows blank ofc
  DoSomething(foo);
  showmessage(foo); // still blank
end;

What I am tr开发者_运维百科ying to do, make it so the paramater of foo can be set. I tried using the var keyword like

DoSomething(var MyVar : Variant)....

but that wont compile.

The reason for this, is DoSomething could assign a string or integer to MyVar which is why it's a variant...


When I do

function Foo(var Bar: variant): boolean;
begin
  Bar := 'beta';
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  a: variant;
begin
  a := 'alpha';
  Foo(a);
  caption := a;
end;

the Caption of the form is beta. So it compiles for me...

You try to send a string as a var variant parameter. You need to send a variant as a var variant parameter, just as the compiler says ([DCC Error] Unit1.pas(35): E2033 Types of actual and formal var parameters must be identical)!

But variants are often not the best things to work with (sub-optimal performance, to mention one thing).

You could do something simple like

type
  TValType = (vtString, vtInteger);
  TData = record
    ValType: TValType;
    ValStr: string;
    ValInt: integer;
  end;

and do

function Foo(var Data: TData): boolean;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜