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)
使用
public Dictionary<string, string> loopThroughNotificationCountQueries() { ... }
Run Code Online (Sandbox Code Playgroud)
或者解释为什么那是不可能的.
| 归档时间: |
|
| 查看次数: |
37066 次 |
| 最近记录: |