首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通用方法写作误区

通用方法写作误区
EN

Stack Overflow用户
提问于 2013-12-30 02:37:51
回答 1查看 96关注 0票数 1

目前,我正在编写一种泛型方法,用于在C#字典中打印键值对;我认为,最好的开始是抓住这种集合的有用性(就像我在HashMaps中所做的那样)。

这里有两种方法在起作用:

代码语言:javascript
复制
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)

问题的方法是:

代码语言:javascript
复制
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

目前我被告知的错误是:

代码语言:javascript
复制
//"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机器上。

任何帮助(抗炎智慧)都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-30 02:44:51

对于一般的where条款,您可以将其定义如下:

代码语言:javascript
复制
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>调用它没有错误:

代码语言:javascript
复制
PrintKeyValuePairs(new Dictionary<string, int> { { "duck", 4 }, { "goose", 5 } });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20832549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档