C#中的实现词典

问题描述 投票:-2回答:1

[在一次采访中被要求实施字典。如何实施?我曾尝试使用数组作为索引使用键来实现它,但是无法实现通用字典。

c# dictionary implementation hashcode
1个回答
0
投票

[有很多方法可以实现类似Dictionary<T1, T2>的类。我将描述一个简单的例子。

  1. 创建一个类和一个存储所有内容的列表。[编辑]我们将比较变量T1的值,以便有一个限制,要求where T1 : IEquatable<T1>
class MyDictionary<T1, T2> where T1 : IEquatable<T1>
{
    private List<(T1 key, T2 val)> m_internal_data;
}
  1. 实现在类中查找值的函数。[编辑]使用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);
    }
}

就是这样。

当然,这不是高度优化的,几乎没有有用的功能。如果您想知道如何写字典更有用,我建议您阅读GitHub dotnet/runtime Dictionary.cs,它包含在.NET Core中。

© www.soinside.com 2019 - 2024. All rights reserved.