C#字典返回类型

use*_*479 5 c# dictionary types return

我在写一些c#代码时遇到了问题,我对c#很新,而且我已经浏览了一下,无法找到解决方案.

我有一个返回Dictionary的方法,我已经将返回类型设置为object,看起来没问题.

    public object loopThroughNotificationCountQueries()
    {
        var countQuery = new Dictionary<string, string>(); ...


        ... return countQuery;
    }
Run Code Online (Sandbox Code Playgroud)

问题出在主要方法中,我试图遍历从字典返回的元素.

                Notification notification = new Notification();

                var countDictionary = notification.loopThroughNotificationCountQueries();


                foreach(KeyValuePair<String, String> entry in countDictionary)
                {
                    ...
                }
Run Code Online (Sandbox Code Playgroud)

我收到一条错误,说"错误2 foreach语句无法对'object'类型的变量进行操作,因为'object'不包含'GetEnumerator'的公共定义"

是因为我没有为字典指定正确的返回类型吗?或者是否有另一种方法来迭代返回对象中的条目?

谢谢你的帮助,斯蒂芬.

Jon*_*eet 10

看看你的方法声明:

public object loopThroughNotificationCountQueries()
Run Code Online (Sandbox Code Playgroud)

这意味着您的countDictionary声明是有效的:

object countDictionary = notification.loopThroughNotificationCountQueries();
Run Code Online (Sandbox Code Playgroud)

...你不能使用foreach带有object这样的.最简单的解决方法是更改​​方法声明,例如

// Note case change as well to follow .NET naming conventions
public IDictionary<string, string> LoopThroughNotificationCountQueries()
Run Code Online (Sandbox Code Playgroud)


Hen*_*man 8

使用

public Dictionary<string, string> loopThroughNotificationCountQueries() { ... }
Run Code Online (Sandbox Code Playgroud)

或者解释为什么那是不可能的.

  • @Oded不可否认我并不是很困难,但我发现Henk的错字很有趣.答案也是有效的,所以我支持我的+1. (3认同)