如何用c#实现自定义类型的dictionary

   2024-10-01 8120
核心提示:在C#中,要实现一个自定义类型的Dictionary,您需要创建一个新的类,并使用泛型字典作为其基础using System;using System.Collec

在C#中,要实现一个自定义类型的Dictionary,您需要创建一个新的类,并使用泛型字典作为其基础

using System;using System.Collections.Generic;public class CustomTypeDictionary<TKey, TValue>{    private Dictionary<TKey, TValue> _internalDictionary;    public CustomTypeDictionary()    {        _internalDictionary = new Dictionary<TKey, TValue>();    }    public void Add(TKey key, TValue value)    {        _internalDictionary.Add(key, value);    }    public bool Remove(TKey key)    {        return _internalDictionary.Remove(key);    }    public bool ContainsKey(TKey key)    {        return _internalDictionary.ContainsKey(key);    }    public TValue this[TKey key]    {        get { return _internalDictionary[key]; }        set { _internalDictionary[key] = value; }    }}

这个示例展示了如何创建一个名为CustomTypeDictionary的自定义类型字典。它包含一个内部字典_internalDictionary,该字典使用泛型参数TKeyTValue。然后,我们在CustomTypeDictionary类中公开了一些常用的方法,如AddRemoveContainsKey以及索引器。

下面是如何使用这个自定义类型字典的示例:

public class Program{    static void Main(string[] args)    {        // 创建一个键为 string 类型,值为 int 类型的自定义字典        var customDict = new CustomTypeDictionary<string, int>();        // 添加元素        customDict.Add("one", 1);        customDict.Add("two", 2);        // 访问元素        Console.WriteLine(customDict["one"]); // 输出: 1        // 删除元素        customDict.Remove("two");        // 检查键是否存在        Console.WriteLine(customDict.ContainsKey("two")); // 输出: False    }}

这个示例展示了如何创建一个自定义类型字典,并向其添加、访问、删除元素以及检查键是否存在。您可以根据需要修改CustomTypeDictionary类,以便为您的特定需求提供更多功能。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号