Beh*_*ooz 5 arrays delphi constants tdictionary
我想TDictionary在Delphi项目中使用a .但我有一个问题,我怎么能创建一个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')
);
...
Run Code Online (Sandbox Code Playgroud)
有没有办法做这个工作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;
...
Run Code Online (Sandbox Code Playgroud)
有人对我有什么建议吗?(对不起,如果我的英语很差!)
您不能编写作为类实例的常量表达式.
但是,由于您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;
Run Code Online (Sandbox Code Playgroud)
我过去做过类似的事情.
| 归档时间: |
|
| 查看次数: |
2224 次 |
| 最近记录: |