如何使用RTTI概念在delphi中设置和获取属性

时间:2018-02-14 04:27:01

标签: delphi-7

我已经完成了我的属性的方法定义作为get和set(fname,lname,address)。我也做了withy propcount但它抛出了一个错误。所以任何人都可以给我一个示例代码我该如何设置运行时的属性。 所以我的问题是我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用变体数据类型,它提供灵活的通用数据类型。

// Show the type of a variant
procedure ShowBasicVariantType(varVar: Variant);
var
  typeString : string;
  basicType  : Integer;

begin
  // Get the Variant basic type :
  // this means excluding array or indirection modifiers
  basicType := VarType(varVar) and VarTypeMask;

  // Set a string to match the type
  case basicType of
    varEmpty     : typeString := 'varEmpty';
    varNull      : typeString := 'varNull';
    varInteger   : typeString := 'varInteger';
    varInt64     : typeString := 'varInt64';
    varByte      : typeString := 'varByte';
    varDate      : typeString := 'varDate';
    varString    : typeString := 'varString';
    varAny       : typeString := 'varAny';
  end;

  // Show the Variant type
  writeln('Variant type  = '+typeString);
end;

在主程序中:

var
  myVar : variant;
begin
  // Assign various values to a Variant
  // and then show the resulting Variant type
  writeln('Variant value = not yet set');
  ShowBasicVariantType(myVar);

  // Simple value
  myVar := 123;
  writeln('Variant value = 123');
  ShowBasicVariantType(myVar);

  // Calculated value using a Variant and a constant
  myVar := myVar + 456;
  writeln('Variant value = 123 + 456');
  ShowBasicVariantType(myVar);

  myVar := 'String '+IntToStr(myVar);
  writeln('Variant value = String 579');
  ShowBasicVariantType(myVar);

  readln;
end.