3

我想按照这篇文章中的建议设置动态数组的长度。我有两个类 TMyClass 和相关的 TChildClass 定义为

TChildClass = class
private
  FField1:  string;
  FField2:  string;
end;

TMyClass = class
private
  FField1:  TChildClass;
  FField2:  Array of TChildClass;
end;

数组扩充实现为

var
  RContext:     TRttiContext;
  RType:        TRttiType;
  Val:          TValue;      // Contains the TMyClass instance
  RField:       TRttiField;  // A field in the TMyClass instance
  RElementType: TRttiType;   // The kind of elements in the dyn array
  DynArr:       TRttiDynamicArrayType;
  Value:        TValue;  // Holding an instance as referenced by an array element
  ArrPointer:   Pointer;
  ArrValue:     TValue;
  ArrLength:    LongInt;
  i:            integer;
begin
  RContext := TRTTIContext.Create;
  try
    RType := RContext.GetType(TMyClass.ClassInfo);
    Val := RType.GetMethod('Create').Invoke(RType.AsInstance.MetaclassType, []);
    RField := RType.GetField('FField2');
    if (RField.FieldType is TRttiDynamicArrayType) then begin 
      DynArr := (RField.FieldType as TRttiDynamicArrayType);
      RElementType := DynArr.ElementType;
      // Set the new length of the array
      ArrValue := RField.GetValue(Val.AsObject);
      ArrLength := 3;   // Three seems like a nice number
      ArrPointer := ArrValue.GetReferenceToRawData;
      DynArraySetLength(ArrPointer, ArrValue.TypeInfo, 1, @ArrLength);
      { TODO : Fix 'Index out of bounds' }
      WriteLn(ArrValue.IsArray, ' ', ArrValue.GetArrayLength);
      if RElementType.IsInstance then begin
        for i := 0 to ArrLength - 1 do begin
          Value := RElementType.GetMethod('Create').Invoke(RElementType.AsInstance.MetaclassType, []);
          ArrValue.SetArrayElement(i, Value);
          // This is just a test, so let's clean up immediatly
          Value.Free;
        end;
      end;
    end;
    ReadLn;
    Val.AsObject.Free;
  finally
    RContext.Free;
  end;
end.

作为 D2010 RTTI 的新手,我怀疑错误可能取决于从类实例中获取 ArrValue,但随后的WriteLn打印结果为“TRUE”,所以我已经排除了这一点。然而,令人失望的是,同样的WriteLn报告称 ArrValue 的大小为 0,这得到了“索引超出范围”的确认 - 我在尝试设置数组中的任何元素时遇到的异常(通过ArrValue.SetArrayElement(i, Value);)。有谁知道我在这里做错了什么?(或者也许有更好的方法来做到这一点?)TIA!

4

2 回答 2

8

动态数组处理起来有点棘手。它们是引用计数的,并且 DynArraySetLength 中的以下评论应该可以阐明这个问题:

// 如果堆对象不是共享的(ref count = 1),只需调整它的大小。否则,我们制作一个副本

您的对象持有一个对它的引用,TValue 也是如此。此外,GetReferenceToRawData 为您提供指向数组的指针。你需要说PPointer(GetReferenceToRawData)^让实际的数组传递给 DynArraySetLength。

一旦你得到它,你可以调整它的大小,但你会留下一个副本。然后你必须将它设置回原始数组。

TValue.Make(@ArrPointer, dynArr.Handle, ArrValue);
RField.SetValue(val.AsObject, arrValue);

总而言之,使用列表而不是数组可能要简单得多。使用 D2010,您可以使用 Generics.Collections,这意味着您可以创建一个TList<TChildClass>TObjectList<TChildClass>并拥有列表类的所有优点,而不会失去类型安全性。

于 2010-03-27T15:39:50.123 回答
0

我认为您应该将数组定义为单独的类型:

TMyArray = array of TMyClass;

并使用它。

从旧的基于 RTTI 的 XML 序列化程序中,我知道您使用的一般方法应该可以工作(D7..2009 测试):

procedure TXMLImpl.ReadArray(const Name: string; TypeInfo: TArrayInformation; Data: Pointer; IO: TParameterInputOutput);
var
  P: PChar;
  L, D: Integer;
  BT: TTypeInformation;
begin
  FArrayType := '';
  FArraySize := -1;
  ComplexTypePrefix(Name, '');
  try
    // Get the element type info.
    BT := TypeInfo.BaseType;
    if not Assigned(BT) then RaiseSerializationReadError; // Not a supported datatype!
    // Typecheck the array specifier.
    if (FArrayType <> '') and (FArrayType <> GetTypeName(BT)) then RaiseSerializationReadError;
    // Do we have a fixed size array or a dynamically sized array?
    L := FArraySize;
    if L >= 0 then begin
      // Set the array
      DynArraySetLength(PPointer(Data)^,TypeInfo.TypeInformation,1,@L);
      // And restore he elements
      D := TypeInfo.ElementSize;
      P := PPointer(Data)^;
      while L > 0 do begin
        ReadElement(''{ArrayItemName},BT,P,IO); // we allow any array item name.
        Inc(P,D);
        Dec(L);
      end;
    end else begin
      RaiseNotSupported;
    end;
  finally
    ComplexTypePostfix;
  end;
end;

希望这可以帮助..

于 2010-03-27T10:06:26.080 回答