我正在关注这个tutorial我正在使用字典,我发现它等同于 Java 中的哈希表。
我像这样创建了我的字典:
private Dictionary<String, Tile> tiles = new Dictionary<String, Tile>();
虽然我的困境是在使用 Dictionary 时我不能使用 get,像这样用 Java 编写:
Tile tile = tiles.get(x + ":" + y);
我如何完成同样的事情。意思是得到 x:y 作为结果?
最佳答案
简答
使用 indexer或 TryGetValue()
方法。如果 key 不存在,则前者会抛出 KeyNotFoundException
。后者返回 false。
确实没有直接等同于 Java Hashtable
get()
方法。这是因为如果 key 不存在,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。
Running Example :
using System;
using System.Collections.Generic;
public class Program
{
private static Dictionary<String, Tile> tiles = new 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; }
}
}
关于c# - 如何像在 Java 中使用 Hashtable 一样使用 C# 泛型字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30246986/