如何像在Java中使用哈希表一样使用c#泛型字典

本文关键字:一样 字典 泛型 哈希表 何像 Java | 更新日期: 2023-09-27 17:49:20

我正在遵循本教程,我正在使用字典,我发现它相当于Java中的哈希表。

我创建了我的字典:

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

虽然我的困境是,当使用字典时,我不能使用get,用Java写的,像这样:

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

我如何完成同样的事情。意思是得到x:y作为结果?

如何像在Java中使用哈希表一样使用c#泛型字典

简短回答

使用索引器或TryGetValue()方法。如果键不存在,则前者抛出一个KeyNotFoundException,后者返回false。

确实没有与Java Hashtable get()方法直接等效的方法。这是因为如果键不存在,Java的get()返回null。

返回指定键映射到的值,如果此映射不包含该键的映射,则返回null。

另一方面,在c#中,我们可以将键映射为空值。如果索引器或TryGetValue()显示与键相关的值为null,那么这并不意味着该键没有被映射。它只是表示键被映射为空。<标题>运行例子:
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; }
    }
}

获取价值的最佳方式是

 bool Dictionary<Key, Value>.TryGetValue(Key key, out Value value);

它将返回布尔值,以确定key是否存在以及value是否被正确引用。

此方法速度很快,因为只有在提供key时才会取出value,因此避免了多次散列和字典搜索。

所以你的代码将是:
private Dictionary<String, Tile> tiles = new Dictionary<String, Tile>();
Tile outValue;
if(tiles.TryGetValue( x + ":" + y, out outValue))
{
     Console.WriteLine("I have this: " + outValue.ToString());
}
else
{
     Console.WriteLine("I have nothing");
}

查看MSDN。