gpt4 book ai didi

C# 字典返回类型

转载 作者:太空狗 更新时间:2023-10-29 22:03:59 25 4
gpt4 key购买 nike

我在编写一些 C# 代码时遇到了问题,我是 C# 的新手,我环顾四周但找不到解决方案。

我有一个返回字典的方法,我将返回类型设置为对象,看起来没问题。

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


... return countQuery;
}

问题出在我试图循环遍历从字典返回的元素的 main 方法中。

                Notification notification = new Notification();

var countDictionary = notification.loopThroughNotificationCountQueries();


foreach(KeyValuePair<String, String> entry in countDictionary)
{
...
}

我收到一条错误消息“错误 2 foreach 语句无法对类型为‘object’的变量进行操作,因为‘object’不包含‘GetEnumerator’的公共(public)定义”

是因为我没有为字典指定正确的返回类型吗?还是有另一种方法可以遍历返回对象中的条目?

感谢您的帮助,斯蒂芬。

最佳答案

查看您的方法声明:

public object loopThroughNotificationCountQueries()

这意味着您的 countDictionary 声明实际上是:

object countDictionary = notification.loopThroughNotificationCountQueries();

...而且您不能将 foreach 与这样的 object 一起使用。最简单的修复是更改方法声明,例如到

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

关于C# 字典返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com