簡體   English   中英

如何實現通用字典類?

[英]How to implement generic dictionary class?

當我嘗試運行以下代碼時, foreach語句在編譯時拋出以下錯誤

無法將類型“字符串”轉換為“ System.Collections.Generic.KeyValuePair>”

namespace myClass
{
public class myDictionary<T>
{
    Dictionary<string, List<T>> dictionary = new Dictionary<string, List<T>>();

    public void Add(string key, T value)
    {
        List<T> list;
        if (this.dictionary.TryGetValue(key, out list))
        {
            list.Add(value);
        }
        else
        {
            list = new List<T>();
            list.Add(value);
            this.dictionary[key] = list;
        }
    }

    public IEnumerable<string> Keys
    {
        get
        {
            return this.dictionary.Keys;
        }
    }

    public List<T> this[string key]
    {
        get
        {
            List<T> list;
            if (!this.dictionary.TryGetValue(key, out list))
            {
                list = new List<T>();
                this.dictionary[key] = list;
            }
            return list;
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return (dictionary as IEnumerable<T>).GetEnumerator();

    }
}

class Program
{
    static void Main()
    {
        myDictionary<string> dictionary = new myDictionary<string>();

        dictionary.Add("One", "AA");
        dictionary.Add("One", "BB");
        dictionary.Add("Two", "CC");
        dictionary.Add("Two", "DD");


        foreach(KeyValuePair<string, List<string>> pair in dictionary)
        {

        }

    }
}

}

請讓我知道我的實現有什么問題。 謝謝你的幫助。

看來問題是:

public IEnumerator<T> GetEnumerator()
{
    return (dictionary as IEnumerable<T>).GetEnumerator();
}

但是,由於字典是列表之一,因此您需要弄清楚應該返回什么。 這是否意味着依次包含所有列表中的所有值? 如果是這樣,我猜:

public IEnumerator<T> GetEnumerator()
{
    return dictionary.Values.SelectMany(x => x).GetEnumerator();
}

但是,如果要返回對,則:

public IEnumerator<KeyValuePair<string, List<T>>> GetEnumerator()
{
    return dictionary.GetEnumerator();
}

暫無
暫無

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

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