c# - 如何像在 Java 中使用 Hashtable 一样使用 C# 泛型字典?

标签 c# dictionary

我正在关注这个tutorial我正在使用字典,我发现它等同于 Java 中的哈希表。

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

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

虽然我的困境是在使用 Dictionary 时我不能使用 get,像这样用 Java 编写:

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

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

最佳答案

简答

使用 indexerTryGetValue()方法。如果 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/

相关文章:

c# - Visual Studio 转义 Linq 语句的第三个条件

c# - Azure DocumentDB异步请求问题

Python:如何从列表中的字典创建 DataFrame 列

c - 需要帮助打印链接列表的内容

python - Pandas Groupby 字典列表到一个字典

ios - 按键将字典数组排序为 Int

java - 插入 Map 的值不会在循环的第二个循环中保留在那里

c# - 在运行时生成接口(interface)实现

c# - 在 Metro (WinRT) 应用程序中使用 PBKDF2 加密

c# - 将 Pchar Delphi DLL 导入到 C#?