詳細Generics Collections TDictionary(2):ContainsKey、ContainsValue、AddOrSetValue、TryGetValue

1509 ワード



unit Unit1;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls;



type

  TForm1 = class(TForm)

    Button1: TButton;

    procedure Button1Click(Sender: TObject);

  end;



var

  Form1: TForm1;



implementation



{$R *.dfm}



uses Generics.Collections;



procedure TForm1.Button1Click(Sender: TObject);

var

  Dictionary: TDictionary<string,Integer>;

  b: Boolean;

  T: Integer;

begin

  Dictionary := TDictionary<string,Integer>.Create();



  { }

  Dictionary.Add('n1', 111);

  Dictionary.Add('n2', 222);

  Dictionary.Add('n3', 333);



  {  Key  }

  b := Dictionary.ContainsKey('n1');

  ShowMessage(BoolToStr(b, True));   {True}

  b := Dictionary.ContainsKey('n4');

  ShowMessage(BoolToStr(b, True));   {False}



  {  Value  }

  b := Dictionary.ContainsValue(111);

  ShowMessage(BoolToStr(b, True));   {True}

  b := Dictionary.ContainsValue(999);

  ShowMessage(BoolToStr(b, True));   {False}



  {  AddOrSetValue  ,   Key  ;   Add  }

  Dictionary.AddOrSetValue('n1', 123);

  ShowMessage(IntToStr(Dictionary['n1'])); {123}



  {  AddOrSetValue  ,   Key   Add}

  Dictionary.AddOrSetValue('n4', 444);

  ShowMessage(IntToStr(Dictionary['n4'])); {444}



  { }

  if Dictionary.TryGetValue('n2', T) then

    ShowMessage(IntToStr(T)); {222}

  

  Dictionary.Free;

end;



end.