原本一直使用 TList, 将定义的一个个 Record 保存在TList 里面, 为了能把某些对象管理起来, 例如一个类的 n 多实例,可以进行索引、查找、释放等

今天刚看到原来已经有了一个叫 TDictionary 对象,用起来挺方便。 挺像我们在DB中定义的 Dictionary 表,Key、Value。  而那个不管Key、Value 都挺发达,允许各种定义的类。

ok,下面官方Demo很通俗易懂,各方法都在:

  1. type
  2. TCity = class
  3. Country: String;
  4. Latitude: Double;
  5. Longitude: Double;
  6. end;
  7.  
  8. const
  9. EPSILON = 0.0000001;
  10.  
  11. var
  12. Dictionary: TDictionary<String, TCity>;
  13. City, Value: TCity;
  14. Key: String;
  15.  
  16. begin
  17. { Create the dictionary. }
  18. Dictionary := TDictionary<String, TCity>.Create;
  19. City := TCity.Create;
  20. { Add some key-value pairs to the dictionary. }
  21. City.Country := 'Romania';
  22. City.Latitude := 47.16;
  23. City.Longitude := 27.58;
  24. Dictionary.Add('Iasi', City);
  25.  
  26. City := TCity.Create;
  27. City.Country := 'United Kingdom';
  28. City.Latitude := 51.5;
  29. City.Longitude := -0.17;
  30. Dictionary.Add('London', City);
  31.  
  32. City := TCity.Create;
  33. City.Country := 'Argentina';
  34. { Notice the wrong coordinates }
  35. City.Latitude := 0;
  36. City.Longitude := 0;
  37. Dictionary.Add('Buenos Aires', City);
  38.  
  39. { Display the current number of key-value entries. }
  40. writeln('Number of pairs in the dictionary: ' +
  41. IntToStr(Dictionary.Count));
  42.  
  43. // Try looking up "Iasi".
  44. if (Dictionary.TryGetValue('Iasi', City) = True) then
  45. begin
  46. writeln(
  47. 'Iasi is located in ' + City.Country +
  48. ' with latitude = ' + FloatToStrF(City.Latitude, ffFixed, 4, 2) +
  49. ' and longitude = ' + FloatToStrF(City.Longitude, ffFixed, 4, 2)
  50. );
  51. end
  52. else
  53. writeln('Could not find Iasi in the dictionary');
  54.  
  55. { Remove the "Iasi" key from dictionary. }
  56. Dictionary.Remove('Iasi');
  57.  
  58. { Make sure the dictionary's capacity is set to the number of entries. }
  59. Dictionary.TrimExcess;
  60.  
  61. { Test if "Iasi" is a key in the dictionary. }
  62. if Dictionary.ContainsKey('Iasi') then
  63. writeln('The key "Iasi" is in the dictionary.')
  64. else
  65. writeln('The key "Iasi" is not in the dictionary.');
  66.  
  67. { Test how (United Kingdom, 51.5, -0.17) is a value in the dictionary but
  68. ContainsValue returns False if passed a different instance of TCity with the
  69. same data, as different instances have different references. }
  70. if Dictionary.ContainsKey('London') then
  71. begin
  72. Dictionary.TryGetValue('London', City);
  73. if (City.Country = 'United Kingdom') and (CompareValue(City.Latitude, 51.5, EPSILON) = EqualsValue) and (CompareValue(City.Longitude, -0.17, EPSILON) = EqualsValue) then
  74. writeln('The value (United Kingdom, 51.5, -0.17) is in the dictionary.')
  75. else
  76. writeln('Error: The value (United Kingdom, 51.5, -0.17) is not in the dictionary.');
  77. City := TCity.Create;
  78. City.Country := 'United Kingdom';
  79. City.Latitude := 51.5;
  80. City.Longitude := -0.17;
  81. if Dictionary.ContainsValue(City) then
  82. writeln('Error: A new instance of TCity with values (United Kingdom, 51.5, -0.17) matches an existing instance in the dictionary.')
  83. else
  84. writeln('A new instance of TCity with values (United Kingdom, 51.5, -0.17) does not match any existing instance in the dictionary.');
  85. City.Free;
  86. end
  87. else
  88. writeln('Error: The key "London" is not in the dictionary.');
  89.  
  90. { Update the coordinates to the correct ones. }
  91. City := TCity.Create;
  92. City.Country := 'Argentina';
  93. City.Latitude := -34.6;
  94. City.Longitude := -58.45;
  95. Dictionary.AddOrSetValue('Buenos Aires', City);
  96.  
  97. { Generate the exception "Duplicates not allowed". }
  98. try
  99. Dictionary.Add('Buenos Aires', City);
  100. except
  101. on Exception do
  102. writeln('Could not add entry. Duplicates are not allowed.');
  103. end;
  104.  
  105. { Display all countries. }
  106. writeln('All countries:');
  107. for Value in Dictionary.Values do
  108. writeln(Value.Country);
  109.  
  110. { Iterate through all keys in the dictionary and display their coordinates. }
  111. writeln('All cities and their coordinates:');
  112. for Key in Dictionary.Keys do
  113. begin
  114. writeln(Key + ': ' + FloatToStrF(Dictionary.Items[Key].Latitude, ffFixed, 4, 2) + ', ' +
  115. FloatToStrF(Dictionary.Items[Key].Longitude, ffFixed, 4, 2));
  116. end;
  117.  
  118. { Clear all entries in the dictionary. }
  119. Dictionary.Clear;
  120.  
  121. { There should be no entries at this point. }
  122. writeln('Number of key-value pairs in the dictionary after cleaning: ' + IntToStr(Dictionary.Count));
  123.  
  124. { Free the memory allocated for the dictionary. }
  125. Dictionary.Free;
  126. City.Free;
  127. readln;
  128. end.

使用 Delphi Xe 的 TDictionary的更多相关文章

  1. delphi 2010与delphi XE破解版的冲突

    在系统中同时安装了Dephi 2010LITE版与Delphi XE lite后,总是会有一个有问题 是因为两者都是读取C:\ProgramData\Embarcadero目录下的license文件, ...

  2. [转载]: delphi中XLSReadWrite控件的使用(2)---delphi XE下安装

    一.下载 官方下载网址: http://www.axolot.com/components/download.htm 从这里可以下载到从Delphi5到DelphiXE全部支持的版本. 二.软件安装 ...

  3. delphi XE Berlin ReadProcessMemory WriteProcessMemory

    delphi  XE,Berlin [dcc32 Error] Unit9.pas(93): E2033 Types of actual and formal var parameters must ...

  4. FastReport for delphi xe 安装步骤

    FastReport for delphi xe 安装步骤 1.先关闭DELPHI:2.下载后解压到一个目录,比如:D:FR:3.打开D:FR,运行recompile.exe ->点击" ...

  5. Delphi XE的firemonkey获取当前文件所在路径的方法

    Delphi XE的firemonkey获取当前文件所在路径的方法 在之前,我们知道有三种方法: ExtractFilePath(ParamStr(0)) ExtractFilePath(Applic ...

  6. Delphi xe 下快捷使用 FastMM 的内存泄露检测功能

    Delphi xe 集成了FastMM,调试程序是的时候可以方便地检查内存泄露了.  使用方法:在project中,添加一行: ReportMemoryLeaksOnShutdown := Debug ...

  7. Delphi XE中使用dbExpress连接MySQL数据库疑难问题解决(对三层的例子配置有帮助)

    Delphi IDE中包含一个Data Explorer的组件,如下图所示: 该组件基于dbExpress(包含TSQLConnection.TSQLDataSet.TSQLQuery.TSQLSto ...

  8. Delphi XE中类成员的访问权限(新增了strict private和strict protected,还有automated)

    Delphi XE中类成员的访问权限共提供了6个关键词来用于限定访问权限:public.private.protected.published.automated strict private . s ...

  9. [转]:Delphi XE中泛型数组的使用范例

    Delphi XE中泛型数组的使用范例,下面的范例简单的使用了泛型字符串数组,如用 TArray 代替 array of Word, 还可以使用 TArray 类提供的算法(就是少了点). uses ...

随机推荐

  1. 【转】关于Android资源文件中出现百分号的问题

    关于Android资源文件中出现百分号的问题 分类: Android JAVA2014-08-01 16:53 1345人阅读 评论(0) 收藏 举报 ANDROID格式化资源文件   目录(?)[+ ...

  2. @MyBatis中的if...else...

    <select id="selectSelective" resultMap="xxx" parameterType="xxx"> ...

  3. Xcode编译WebApps找不到js的错误解决办法<转>

    使用Xcode做WebApps时,使用UIWebview来调用一个页面,有时会遇到问题,其一就是编译的时候出现黄色感叹号的Warning,js文件都报错:warning: no rule to pro ...

  4. css3画图之大白(●—●)

    把大白送给你~ <!DOCTYPE html> <html> <head> <title>大白</title> <meta http- ...

  5. MVC项目实践,在三层架构下实现SportsStore-09,ASP.NET MVC调用ASP.NET Web API的查询服务

    ASP.NET Web API和WCF都体现了REST软件架构风格.在REST中,把一切数据视为资源,所以也是一种面向资源的架构风格.所有的资源都可以通过URI来唯一标识,通过对资源的HTTP操作(G ...

  6. Java Lock ReentrantLock ReentrantReadWriteLock

    Lock与Synchronized的区别:   1)Lock是一个接口,而synchronized是Java中的关键字,synchronized是内置的语言实现: 2)synchronized在发生异 ...

  7. string函数分析

    string函数分析string函数包含在string.c文件中,经常被C文件使用.1. strcpy函数原型: char* strcpy(char* str1,char* str2);函数功能: 把 ...

  8. Vue.2.0.5-组件

    什么是组件? 组件(Component)是 Vue.js 最强大的功能之一.组件可以扩展 HTML 元素,封装可重用的代码.在较高层面上,组件是自定义元素, Vue.js 的编译器为它添加特殊功能.在 ...

  9. PDB重命名

    PDB重命名 将PDB clonedb重命名为rdb SQL> select name,open_mode from v$pdbs; NAME OPEN_MODE --------------- ...

  10. 【转】分布式理论-CAP理论

    一 CAP理论简述 CAP (Consistency, Availability, Partition  Tolerance,) 理论是NoSQL数据库管理系统构建的基础.     强一致性:等同于所 ...