Tell me how to create, and is it possible, an array where the index is a string? MyArray['index'] ?

If not, then what is the structure of TIBQuery with its IBQ['some_field_name'] conversion IBQ['some_field_name'] ?

  • for such purposes TStringList is usually used. a la sl.values['index'] := 'qwe'; - teran
  • one
    or TDictionary<string, T> from Generics.Collections - teran
  • and the treatment itself can be implemented manually. - teran
  • In TIBQuery [] property is explained by an index argument with a string index argument. And already inside it something like FieldIndexByName() called. - nick_n_a February
  • @nick_n_a "declared index with string argument of index." Where did you see it, I also want so !!! The question is how to make a similar design! - JVic

1 answer 1

By themselves, arrays do not support string keys. However, there are many structures that offer such functionality. One of the common solutions for storing key-value pairs used in components is the various descendants of the TStrings class and the most commonly used one is the TStringList from the classes module.

 sl := TStringList.Create(); try sl.values['index'] := 'qwe'; writeln(sl.Values['index']); finally sl.Free(); end; 

In general, the main data structure in similar situations is the dictionary TDictionary<TKey, TValue> . This is a generic (generic, generics, generic) type with parameterized types of keys and values. For example, the following code can be used to store string keys and integer values.

 d := TDictionary<string, integer>.Create(); try d.AddOrSetValue('key', 123); writeln(d['key']); finally d.Free(); end; 

Dictionaries, along with TList lists, TStack stack and TQueue queues TQueue are the primary storage structures. Their functionality is quite extensive.

As for the indexed access to some object data, this can be implemented manually in any class.
To do this, you must implement an index property, and add the modifier default to it. It is obvious that the default-property, which allows not to specify the name of the property when accessing, can be only one.

 TTest = class(TObject) private function getValue(key:string):integer; procedure setValue(key: string; value: integer); public property Values[key: string]: integer read getValue write setValue; default; end; 

Implementing get/set-value methods is as simple as possible.

 function TTest.getValue(key: string):integer; begin result := 123; end; procedure TTest.setValue(key:string; value : integer); begin raise Exception.Create('not implemented'); end; 

In this implementation, any reference on a string key will return 123 :

 t := TTest.Create(); try writeln(t['index']); finally t.Free(); end; 
  • Thank you very much!! - JVic
  • why empty brackets () in Create & Free? Onex is not needed - Zam
  • @Zam a matter of taste. I always write parentheses for methods, so it’s clearer to me in the code to distinguish method calls from possible calls to variables. - teran