我有个问题.我是Delphi 2010中运行时类型信息的新手.我需要将动态数组的长度设置为TValue.你可以看到代码.
Type TMyArray = array of integer; TMyClass = class publihed function Do:TMyArray; end; function TMyClass.Do:TMyArray; begin SetLength(Result,5); for i:=0 to 4 Result[i]=3; end; ....... ....... ...... y:TValue; Param:array of TValue; ......... y=Methods[i].Invoke(Obj,Param);//delphi give me a DynArray type kind,is working,Param works to any functions. if Method[i].ReturnType.TypeKind = tkDynArray then//is working... begin I want to set length for y to 10000//i don't know how to write. end;
我不喜欢Generics Collections.
解决方法
TValue不是为了对其内容进行任意操作而设计的(如果是这样的话,它将有更多帮助器用于设置记录字段等),而是用于在具体静态类型和动态RTTI之间传输值.在这方面,TValue.SetArrayElement是一个异常,事后看来,或许不应该被包括在内.但是,你问的是可能的:
uses Rtti; type TMyArray = array of Integer; TMyClass = class function Go: TMyArray; end; function TMyClass.Go: TMyArray; var i: Integer; begin SetLength(Result,5); for i := 0 to 4 do Result[i] := 3; end; procedure P; var ctx: TRttiContext; v: TValue; len: Longint; i: Integer; begin v := ctx.GetType(TMyClass).GetMethod('Go').Invoke(TMyClass.Create,[]); Writeln(v.ToString); len := 10; DynArraySetLength(PPointer(v.GetReferenceToRawData)^,v.TypeInfo,1,@len); Writeln(v.GetArrayLength); for i := 0 to v.GetArrayLength - 1 do Writeln(v.GetArrayElement(i).ToString); end; begin P; end.