簡體   English   中英

在 c# 中實現字典

[英]Implement Dictionary in c#

我在一次采訪中被問到實現字典。如何實現它?我嘗試使用索引作為鍵使用數組來實現它。但是無法實現通用字典。

有很多方法可以實現 class ,例如Dictionary<T1, T2>
我將描述一個簡單的。

  1. 創建一個 class 和一個存儲所有內容的 List。
    [編輯] 我們將比較變量 T1 的值,以便限制, where T1: IEquatable<T1>是必需的。
class MyDictionary<T1, T2> where T1 : IEquatable<T1>
{
    private List<(T1 key, T2 val)> m_internal_data;
}
  1. 實現一個 function,它在 class 中找到一個值。
    [編輯] 使用Equals function。 使用==會導致錯誤。
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. 實現一個分配值的 function。
    [編輯] 也使用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 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM