C# 一般写作方法
我目前正在编写一个泛型方法来打印C#Dictionary中的键值对;我认为这是掌握此类集合的有用性的最佳起点(就像我在Java中使用HashMaps所做的那样) 这里有两种方法:C# 一般写作方法,c#,generics,generic-programming,generic-collections,C#,Generics,Generic Programming,Generic Collections,我目前正在编写一个泛型方法来打印C#Dictionary中的键值对;我认为这是掌握此类集合的有用性的最佳起点(就像我在Java中使用HashMaps所做的那样) 这里有两种方法: ListWordCount(string text){// Code body} // Returns a Dictionary<string, int> with the number of occurrences // Works exactly as intended (its from one
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)
ListWordCount(字符串文本){//code body}
//返回包含出现次数的字典
//完全按照预期工作(来自我的一本教科书)
问题方法:
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
publicstaticvoidprintKeyValuePairs(字典dict)
{
foreach(dict中的KeyValuePair项)
{
WriteLine(“{0}:{1}”,item.Key,item.Value);
}
}
// ... 稍后有几行
PrintKeyValuePairs(ListWordCount(“Duck,Duck,Duck,goose”);//我们从哪里得到错误
我被告知的当前错误是:
//"Argument 1:
//Cannot convert from 'System.Collections.Generic.Dictionary<string, int>' to
//'System.Collections.Generic.Dictionary<System.IComparable,System.IComparable>' "
/“参数1:
//无法从“System.Collections.Generic.Dictionary”转换为
//“System.Collections.Generic.Dictionary”
。。最后我检查了一下,string和int都实现了“IComparable”,所以我可能误解了继承的本质,但我以前做过一些非常类似的事情,那不是泛型。我想知道如何纠正这个问题,以便将来可以防止这种类型转换错误,或者只是编写这种通用逻辑的更好方法
如果有必要的话,我现在在VisualStudio2013的Windows8.1机器上
任何帮助(抗炎智慧)都将不胜感激。对于通用型,您将其定义如下:
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);
}
}
publicstaticvoidprintKeyValuePairs(字典dict)
其中T:i可比较
其中U:i可比较
{
foreach(dict中的KeyValuePair项)
{
WriteLine(“{0}:{1}”,item.Key,item.Value);
}
}
使用字典调用它没有错误:
PrintKeyValuePairs(new Dictionary<string, int> { { "duck", 4 }, { "goose", 5 } });
PrintKeyValuePairs(新字典{{“duck”,4},{“goose”,5});
为什么该方法仍然需要i可比较的
实现者?没有必要..当我最初尝试使用“PrintKeyValuePairs(字典)”时,我去掉了“where”部分。看起来我还有很多东西要学..谢谢bunch@SteveTheCoder在当前的实现中,您所需要的只是对象有一个ToString()不需要IComparable的实现。在这种情况下,您实际上不需要where子句,除非添加了一些未注明的其他功能。