我正在关注这个
tutorial,我正在使用我发现的字典,它相当于Java中的Hashtable.
我像这样创建了我的词典:
- private Dictionary<String,Tile> tiles = new Dictionary<String,Tile>();
虽然我的困境是当使用Dictionary时我不能使用get,用Java编写如下:
- Tile tile = tiles.get(x + ":" + y);
我如何完成同样的事情.意味着获得x:y作为结果?
解决方法
简答
使用indexer或TryGetValue()
方法.如果密钥不存在,则前者抛出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.
- using System;
- using System.Collections.Generic;
- public class Program
- {
- private static Dictionary<String,Tile>();
- public static void Main()
- {
- // add two items to the dictionary
- tiles.Add("x",new Tile { Name = "y" });
- tiles.Add("x:null",null);
- // indexer access
- var value1 = tiles["x"];
- Console.WriteLine(value1.Name);
- // TryGetValue access
- Tile value2;
- tiles.TryGetValue("x",out value2);
- Console.WriteLine(value2.Name);
- // indexer access of a null value
- var value3 = tiles["x:null"];
- Console.WriteLine(value3 == null);
- // TryGetValue access with a null value
- Tile value4;
- tiles.TryGetValue("x:null",out value4);
- Console.WriteLine(value4 == null);
- // indexer access with the key not present
- try
- {
- var n1 = tiles["nope"];
- }
- catch(KeyNotFoundException e)
- {
- Console.WriteLine(e.Message);
- }
- // TryGetValue access with the key not present
- Tile n2;
- var result = tiles.TryGetValue("nope",out n2);
- Console.WriteLine(result);
- Console.WriteLine(n2 == null);
- }
- public class Tile
- {
- public string Name { get; set; }
- }
- }