目前,我正在编写一种泛型方法,用于在C#字典中打印键值对;我认为,最好的开始是抓住这种集合的有用性(就像我在HashMaps中所做的那样)。
这里有两种方法在起作用:
ListWordCount(string text){// Code body}
// Returns a Dictionary<string, int> with the number of occurrences
// Works exactly as intended (its from one of my textbooks)问题的方法是:
public static void PrintKeyValuePairs(Dictionary<IComparable, IComparable> dict)
{
foreach (KeyValuePair<IComparable, IComparable> item in dict)
{
Console.WriteLine("{0}: {1}", item.Key, item.Value);
}
}
// ... Some lines later
PrintKeyValuePairs( ListWordCount("Duck, duck, duck, goose") ); // Where we get the error目前我被告知的错误是:
//"Argument 1:
//Cannot convert from 'System.Collections.Generic.Dictionary<string, int>' to
//'System.Collections.Generic.Dictionary<System.IComparable,System.IComparable>' "。。最后我检查了一下,string和int实现了‘I比较法’,所以我可能误解了继承的性质,但是我做了一些非常类似的事情,以前都不是泛型。我想知道如何纠正这个问题,这样我就可以在将来防止这类类型转换错误,或者只是编写这个一般逻辑的更好的方法。
如果有关系,我在Visual 2013的Windows8.1机器上。
任何帮助(抗炎智慧)都将不胜感激。
发布于 2013-12-30 02:44:51
对于一般的where条款,您可以将其定义如下:
public static void PrintKeyValuePairs<T, U>(Dictionary<T, U> dict)
where T : IComparable
where U : IComparable
{
foreach (KeyValuePair<T, U> item in dict)
{
Console.WriteLine("{0}: {1}", item.Key, item.Value);
}
}用Dictionary<string, int>调用它没有错误:
PrintKeyValuePairs(new Dictionary<string, int> { { "duck", 4 }, { "goose", 5 } });https://stackoverflow.com/questions/20832549
复制相似问题