简体   繁体   English

按默认值创建一个常量的TDictionary数组

[英]Create a constant array of TDictionary by default value

I want to use the a TDictionary in a Delphi project. 我想在Delphi项目中使用TDictionary But I've a problem,how i can Create a constant array of TDictionary by default value ? 但我有一个问题,我怎么能默认值创建一个常量的TDictionary数组?

For example i want to allocate 4 item for a dictionary such as bellow code (for constant array of TItem ) : 例如,我想为字典分配4项,如波纹管代码(对于TItem常量数组):

...
type
  TItem = record
    _Key: string;
    _Value: string;
  end;
var
  Dic: array [0..3]of TItem=(
  (_Key:'A' ; _Value:'Apple'),
  (_Key:'B' ; _Value:'Book'),
  (_Key:'C' ; _Value:'C++'),
  (_Key:'D' ; _Value:'Delphi')
  );
...

Is there any way to do this work with TDictionary ? 有没有办法用TDictionary做这个工作? I want to create a constant array of Dic (but) such as bellow structure . 我想创建一个Dic (但)的常量数组,例如波纹管结构。

  ...
    var
      Dic: TDictionary<string, string>;
    begin
      Dic := TDictionary<string, string>.Create;
      try
        Dic.Add('A', 'Apple');
        Dic.Add('B', 'Book');
        Dic.Add('C', 'C++');
        Dic.Add('D', 'Delphi');
      finally
         ///
      end;
    ...

Anyone have any advice for me? 有人对我有什么建议吗? (Excuse me if my English is poor !) (对不起,如果我的英语很差!)

You cannot write a constant expression that is an instance of a class. 您不能编写作为类实例的常量表达式。

Yet, since your TDictionary is a collection of String which is a type that you can create constants with, you could just build your TDictionary at run time from your constants. 但是,由于您的TDictionaryString的集合,这是一种可以创建常量的类型,您可以在运行时从常量构建TDictionary You could use records as in your question, but I like arrays: 您可以在问题中使用记录,但我喜欢数组:

{$IFDEF WHATEVER}
type
  TDictConstant = array[0..3, 0..1] of String;
const
  DICT_CONSTANT: TDictConstant = (('A', 'Apple'), ('B', 'Book'), ('C', 'C++'), ('D', 'Delphi'));
{$ELSE}
// If you want it "blank" for one config
type
  TDictConstant = array[0..0, 0..1] of String;
const
  DICT_CONSTANT: TDictConstant = (('', ''));
{$ENDIF}
var
  Dic: TDictionary<string, string>;

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  Dic := TDictionary<string, string>.Create;
  for i := 0 to High(DICT_CONSTANT) do
  begin
    // Ignore the "blank" ones
    if (DICT_CONSTANT[i][0] <> '') or (DICT_CONSTANT[i][1] <> '') then
    begin
      Dic.Add(DICT_CONSTANT[i][0], DICT_CONSTANT[i][1]);
    end;
  end;
end;

I've done similar in the past. 我过去做过类似的事情。

You cannot write a constant expression that is an instance of a class. 您不能编写作为类实例的常量表达式。 So what you are attempting to do is not possible. 所以你试图做的事情是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM