MicroTip#4 const Args: array of ... 的应用

来源:互联网 发布:淘宝其他费用 编辑:程序博客网 时间:2024/05/28 03:01
MicroTip#4 const Args: array of ... 的应用

// Test in Delphi6 up2
// Wrtten by SkyJacker 2007.03.21
// QQ Discuss Group: 130970

// 注:本人发布的源码,仅供参考,不保证无Bug。
// 非常欢迎讨论 Code 或 Bug 问题。

应用要求:用一个函数实现对 TListView 添加一行数据。
特点:列的个数不固定。

因此,用开放数组参数 const Args: array of  是个不错的办法。
const Args: array of 的形式有两种: 固定类型和可变类型。

实现了如下两个函数:
procedure ListAddLine(const Args: array of string; AListView: TListView);
{* 在列表中增加一行}
procedure ListAddLineT(const Args: array of const; AListView: TListView);
{* 在列表中增加一行, 多类型版}

使用方法:
  ListAddColumn('测试1', lvData);
  ListAddColumn('测试2', lvData);
  ListAddColumn('测试3', lvData);   

  ListAddLine([], LvData);
  ListAddLine(['1'], LvData);
  ListAddLine(['1', '2'], LvData);
  ListAddLine(['1', '2', '3'], LvData);

  ListAddLineT([], LvData);
  ListAddLineT(['2'], LvData);
  ListAddLineT(['2', 22.2], LvData);
  ListAddLineT(['2', 33, 3.01], LvData);

Source:

// 在列表中增加一列头
procedure ListAddColumn(const AColumnCpation: string; AListView: TListView);
begin
  if Assigned(AListView) then
    AListView.Columns.Add.Caption := AColumnCpation;
end;

// 在列表中增加一行
procedure ListAddLine(const Args: array of string; AListView: TListView);
var
  I: Integer;
begin
  if High(Args) < 0 then
    Exit;
  with AListView.Items.Add do
  begin
    Caption := Args[0];
    for I := Low(Args) + 1 to High(Args) do
    begin
      SubItems.Add(Args[I]);
    end;
  end;
end;

// 在列表中增加一行, 多类型版
procedure ListAddLineT(const Args: array of const; AListView: TListView);
var
  I: Integer;
  S: string;
begin
  with AListView.Items.Add do
  begin
    for I := Low(Args) to High(Args) do
    begin
      case Args[I].VType of
        vtInteger:
          S := IntToStr(Args[I].VInteger);
        vtBoolean:
          if Args[I].VBoolean then
            S := '1'
          else
            S := '0';
        vtChar:
          S := Args[I].VChar;
        vtExtended:
          S := FloatToStr(Args[I].VExtended^);
        vtString, vtAnsiString:
          S := Args[I].VString^;
        vtWideChar:
          S := Args[I].VWideChar;
      else
        S := 'UnKnown Type';
      end;
      if I = 0 then
        Caption := S
      else
        SubItems.Add(S);
    end;
  end;
end;

 
原创粉丝点击