我如何使用C#泛型字典,就像在Java中使用Hashtable一样?

前端之家收集整理的这篇文章主要介绍了我如何使用C#泛型字典,就像在Java中使用Hashtable一样?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在关注这个 tutorial,我正在使用我发现的字典,它相当于Java中的Hashtable.

我像这样创建了我的词典:

  1. private Dictionary<String,Tile> tiles = new Dictionary<String,Tile>();

虽然我的困境是当使用Dictionary时我不能使用get,用Java编写如下:

  1. Tile tile = tiles.get(x + ":" + y);

我如何完成同样的事情.意味着获得x:y作为结果?

解决方法

简答

使用indexerTryGetValue()方法.如果密钥不存在,则前者抛出KeyNotFoundException,后者返回false.

实际上没有直接等同于Java Hashtable get()方法.这是因为如果密钥不存在,Java的get()将返回null.

Returns the value to which the specified key is mapped,or null if this map contains no mapping for the key.

另一方面,在C#中,我们可以将键映射到空值.如果索引器或TryGetValue()表示与键关联的值为null,则表示该键未映射.它只是意味着键被映射为null.

Running Example

  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Program
  5. {
  6. private static Dictionary<String,Tile>();
  7. public static void Main()
  8. {
  9. // add two items to the dictionary
  10. tiles.Add("x",new Tile { Name = "y" });
  11. tiles.Add("x:null",null);
  12.  
  13. // indexer access
  14. var value1 = tiles["x"];
  15. Console.WriteLine(value1.Name);
  16.  
  17. // TryGetValue access
  18. Tile value2;
  19. tiles.TryGetValue("x",out value2);
  20. Console.WriteLine(value2.Name);
  21.  
  22. // indexer access of a null value
  23. var value3 = tiles["x:null"];
  24. Console.WriteLine(value3 == null);
  25.  
  26. // TryGetValue access with a null value
  27. Tile value4;
  28. tiles.TryGetValue("x:null",out value4);
  29. Console.WriteLine(value4 == null);
  30.  
  31. // indexer access with the key not present
  32. try
  33. {
  34. var n1 = tiles["nope"];
  35. }
  36. catch(KeyNotFoundException e)
  37. {
  38. Console.WriteLine(e.Message);
  39. }
  40.  
  41. // TryGetValue access with the key not present
  42. Tile n2;
  43. var result = tiles.TryGetValue("nope",out n2);
  44. Console.WriteLine(result);
  45. Console.WriteLine(n2 == null);
  46. }
  47.  
  48. public class Tile
  49. {
  50. public string Name { get; set; }
  51. }
  52. }

猜你在找的C#相关文章