Delphi 中 "位" 的使用(3) TBits


TBits 直接继承自 TObject, 它只扩充出 2 个属性、1 个方法:

TBits.Size    //需要使用的 "位" 数
TBits.Bits[]  //默认的数组属性, 用于读写每个 "位"; 用 True 表示 1, 用 False 表示 0
TBits.OpenBit //获取第一个是 0 的 "位" 的位置


简单示例:

procedure TForm1.Button1Click(Sender: TObject);
var
  bs: TBits;
begin
  bs := TBits.Create;
  {使用前应该先设置 Size, 这是需要容纳的 "位" 的数目}
  bs.Size := 3;
  {赋值、取值都通过默认的数组属性 bs.Bits[]}
  bs[0] := True;
  bs[1] := False;
  bs[2] := True;
  ShowMessage(BoolToStr(bs[1], True)); {False}
  ShowMessage(BoolToStr(bs[2], True)); {True}
  {OpenBit 方法获取的是第一个是 0 的位置}
  ShowMessage(IntToStr(bs.OpenBit));   {1; 这表示是第二个位}
  bs.Free;
end;


OpenBit 方法的主要用途 - 把第一个非 1 的 "位" 设置为 1:

var bs: TBits;

procedure TForm1.Button1Click(Sender: TObject);
var
  i: Integer;
  fn: Integer;
begin
  {初始化并赋随机值}
  bs.Size := 8;
  for i := 0 to bs.Size do bs[i] := Boolean(Random(2));

  {把第一个非 1 的 "位" 设置为 1}
  fn := bs.OpenBit;
  if fn <= bs.Size then bs[fn] := True;
end;

initialization
  bs := TBits.Create;
  Randomize;
finalization
  if Assigned(bs) then bs.Free;

end.


用 TBits 实现前面的例子(窗体设计与测试效果同前):

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, CheckLst;

type
  TForm1 = class(TForm)
    CheckListBox1: TCheckListBox;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var bs: TBits;

procedure TForm1.FormCreate(Sender: TObject);
begin
  CheckListBox1.Items.CommaText := 'A,B,C,D,E,F,G,H';
  Button1.Caption := '保存状态';
  Button2.Caption := '恢复状态';
  Button3.Caption := '全选';
  Button4.Caption := '全不选';
  Button1.Tag := 1;
  Button2.Tag := 2;
  Button3.Tag := 3;
  Button4.Tag := 4;
  Button2.OnClick := Button1.OnClick;
  Button3.OnClick := Button1.OnClick;
  Button4.OnClick := Button1.OnClick;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  i: Integer;
begin
  for i := 0 to CheckListBox1.Count - 1 do
    case TButton(Sender).Tag of
      1: bs[i] := CheckListBox1.Checked[i];
      2: CheckListBox1.Checked[i] := bs[i];
      3: CheckListBox1.Checked[i] := True;
      4: CheckListBox1.Checked[i] := False;
    end;
end;

initialization
  bs := TBits.Create;
finalization
  if Assigned(bs) then bs.Free;

end.


Delphi 在下面单元的源码中都有 TBits 的应用:
Menus、Buttons、ComCtrls、DBClient、DBTables、DBCommon、DesignEditors

原文地址:https://www.cnblogs.com/del/p/1730119.html