、のforeach文は、コンパイル時に汎用辞書クラスの実装方法は?私は、次のコードを実行しようとすると
Cannot convert type 'string' to '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)
{
}
}
}
}
を以下のエラーを投げている私の実装と間違っているものを教えてください。ご協力いただきありがとうございます。
あなたのforeach文は 'MyDictionaryは' IEnumerableをを実装する予定> '。だから、もしそれを動作させたいのであれば、これを実装する必要があります。おそらくプライベートな 'Dictionary >' –
Joe