如何通过名称获取属性值

时间:2013-06-16 16:59:59

标签: delphi properties devexpress styling

我有一个类,其中包含一些我想列出的已发布属性。 属性为TcxCustomStyle类型,来自DevExpress样式。 我使用以下代码将名称添加到memdata表中,如果我删除所有相关的TcxCustomStyle,它就可以正常工作。

问题是如何获取TcxCustomStyle类型的属性的值?

很可能这是我身边的简单错误 - 但我无法弄清楚是什么。

procedure TfrmMain.ListProperties;
var
  ctx: TRttiContext;
  rType: TRttiType;
  rProp: TRttiProperty;
  i: integer;
  Value: TcxCustomStyle;
begin
  i := 1;
  memProperties.DisableControls;
  try
    memProperties.Close;
    memProperties.Open;

    rType := ctx.GetType(Settings.Styling.ClassType);
    for rProp in rType.GetProperties do
      begin
        Value := TcxCustomStyle(rProp.GetValue(Self).AsObject);
        memProperties.AppendRecord([i, rProp.Name, Value.Name]);
        Inc(i);
      end;

  finally
    ctx.Free;
    memProperties.EnableControls;
  end;
end;

2 个答案:

答案 0 :(得分:1)

有点难以确定是什么问题,因为我们缺少很多细节。尤其是您没有包含有关类型的信息,也没有错误消息。

跳出来的是你将rType设置为Settings.Styling.ClassType指定的类型。然后,遍历其属性并从类型为Self的实例TfrmMain中读取它们。那看起来不对。传递给GetValue的参数必须是Settings.Styling.ClassType类型。我希望你需要将另一个实例传递给GetValue

我还会质疑使用未经检查的演员TcxCustomStyle(...)。这对你来说很难。使用经过检查的演员:... as TcxCustomStyle

您的代码还假定Settings.Styling.ClassType的所有属性都属于TcxCustomStyle类型。也许这是一个合理的假设,我不知道。

答案 1 :(得分:0)

花了一些时间查看旧代码后,我将该函数重写为以下工作代码。 现在我只想弄清楚如何在类中存储每个属性的描述 - 我已经看到完成了。我需要TcxCustomStyle值和我可以显示的描述。但这是另一个问题。

procedure TfrmMain.ListProperties;
var
  ctx       : TRttiContext;
  lType     : TRttiType;
  lProperty : TRttiProperty;
  i         : integer;
  Value     : TcxCustomStyle;
begin
  i := 1;
  memProperties.DisableControls;
  ctx := TRttiContext.Create;
  try
    memProperties.Close;
    memProperties.Open;

    lType := ctx.GetType(Settings.Styling.ClassType);
    for lProperty in lType.GetProperties do
      begin
        Value := TcxCustomStyle(lProperty.GetValue(Settings.Styling).AsObject);
        memProperties.AppendRecord([i, lProperty.Name, Value.Name]);
        Inc(i);
      end;

  finally
    ctx.Free;
    memProperties.EnableControls;
  end;
end;
相关问题