在 C# 中实现字典

Implement Dictionary in c#

我在面试中被要求实现 dictionary.How 实现它?我尝试使用索引作为键使用 array.But 实现它无法实现通用字典。

有很多方法可以实现像 Dictionary<T1, T2> 这样的 class。
我会描述一个简单的。

  1. 创建一个class和一个存储所有内容的列表。
    [编辑] 我们将比较变量 T1 值,因此需要限制,where T1 : IEquatable<T1>
class MyDictionary<T1, T2> where T1 : IEquatable<T1>
{
    private List<(T1 key, T2 val)> m_internal_data;
}
  1. 实现一个在 class.
    中查找值的函数 [编辑] 使用 Equals 函数。使用 == 会导致错误。
public T2 Find(T1 key)
{
    // Looking for a content.
    foreach (var content in m_internal_data)
    {
        if (content.key.Equals(key))
        {
            return content.val;
        }
    }
    // It reaches here when there is no content which has the same key.
    // Then, I recommend to throw an exception or return a default value of T2.
    return default(T2);
}
  1. 实现一个赋值函数。
    [编辑] 也使​​用 Equals
public void Store(T1 key, T2 val)
{
    // Looking for a content. If exists, store a new value.
    for (int i = 0; i < m_internal_data.Count; i++)
    {
        if (m_internal_data[i].key.Equals(key))
        {
            var content = m_internal_data[i];
            content.val = val;
            m_internal_data[i] = content;
            return;
        }
    }
    // Create a new key.
    m_internal_data.Add((key, val));
}
  1. 使其能够使用方括号访问值。调用之前的函数即可。
public T2 this[T1 key]
{
    get => Find(key);
    set
    {
        Store(key, value);
    }
}

就是这样。

当然,这不是高度优化,也没有什么有用的功能。如果你想知道怎样写Dictionary更有用,推荐你阅读 GitHub dotnet/runtime Dictionary.cs,包含在 .NET Core 中。