我想在 Delphi 项目中使用 TDictionary
。但我有一个问题,如何按默认值创建 TDictionary
常量数组?
例如,我想为字典分配 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')
);
...
有什么方法可以使用 TDictionary
来完成这项工作吗?
我想创建一个 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;
...
有人可以给我一些建议吗? (如果我的英语很差,请原谅!)
最佳答案
您不能编写作为类实例的常量表达式。
但是,由于您的 TDictionary
是 String
的集合,它是一种可以用来创建常量的类型,因此您可以构建您的 TDictionary
> 在运行时根据您的常量。您可以像问题中那样使用记录,但我喜欢数组:
{$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;
我过去也做过类似的事情。
关于arrays - 创建一个默认值的 TDictionary 常量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19666793/