c#

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

小樊
83
2024-08-27 15:03:29
栏目: 编程语言

在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类,以便为您的特定需求提供更多功能。

0
看了该问题的人还看了