加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:28:53 所属栏目:百科 来源:网络整理
导读:我正在关注这个 tutorial,我正在使用我发现的字典,它相当于Java中的Hashtable. 我像这样创建了我的词典: private DictionaryString,Tile tiles = new DictionaryString,Tile(); 虽然我的困境是当使用Dictionary时我不能使用get,用Java编写如下: Tile tile
我正在关注这个 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.

Running Example:

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; }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读