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

E.A*_*O.S 6 c# dictionary

我正在学习本教程,我正在使用我发现的字典,它相当于Java中的Hashtable.

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

private Dictionary<String, Tile> tiles = new Dictionary<String, Tile>();
Run Code Online (Sandbox Code Playgroud)

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

Tile tile = tiles.get(x + ":" + y);
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*tin 9

简答

使用索引器TryGetValue()方法.如果密钥不存在,则前者抛出a KeyNotFoundException而后者返回false.

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

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

另一方面,在C#中,我们可以将键映射到空值.如果索引器或者TryGetValue()说与键关联的值为null,那么这并不意味着键未映射.它只是意味着键被映射为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; }
    }
}
Run Code Online (Sandbox Code Playgroud)