C# Dictionary Return Type
我在写一些C代码时遇到了问题,我对C代码还比较陌生,我四处看看,找不到解决方案。
我有一个返回字典的方法,我将返回类型设置为Object,看起来还可以。
| 1 2 3 4 5 6 7 |     public object loopThroughNotificationCountQueries() { var countQuery = new Dictionary<string, string>(); ... ... return countQuery; } | 
问题出在主方法中,我试图循环遍历从字典返回的元素。
| 1 2 3 4 5 6 7 8 9 |                 Notification notification = new Notification(); var countDictionary = notification.loopThroughNotificationCountQueries(); foreach(KeyValuePair<String, String> entry in countDictionary) { ... } | 
我收到一条错误消息:"error 2 foreach语句无法对"object"类型的变量进行操作,因为"object"不包含"getEnumerator"的公共定义。"
是因为我没有为字典指定正确的返回类型吗?或者,是否有其他方法来遍历返回对象中的条目?
谢谢你的帮助,史蒂芬。
看看你的方法声明:
| 1 | public object loopThroughNotificationCountQueries() | 
这意味着你的
| 1 | object countDictionary = notification.loopThroughNotificationCountQueries(); | 
…你不能把
| 1 2 | // Note case change as well to follow .NET naming conventions public IDictionary<string, string> LoopThroughNotificationCountQueries() | 
使用
| 1 | public Dictionary<string, string> loopThroughNotificationCountQueries() { ... } | 
或者解释为什么不可能。
| 1 2 3 4 5 6 7 | public IDictionary<string, string> loopThroughNotificationCountQueries() { var countQuery = new Dictionary<string, string>(); ... ... return countQuery; } | 
您不能使用方法签名的原因如下?是否总是返回具有字符串键类型和字符串数据类型的字典?
| 1 | public Dictionary<string, string> loopThroughNotificationCountQueries() | 
是的,应该是:
| 1 2 3 | public IDictionary<string, string> loopThroughNotificationCountQueries() { } | 
你只能通过
因此,如果由于某种原因您不能更改
你的
| 1 2 3 4 5 6 7 | public Dictionary<string, string> loopThroughNotificationCountQueries() { var countQuery = new Dictionary<string, string>(); ... ... return countQuery; } | 
您不应该返回非私有方法中的字典,它将公开类型以及所有方法和属性,如果您不需要它们,并且在大多数情况下不应该返回,不要返回。打开fxcop,它会因为你这样做而对你大喊大叫。
很多方法绕过它,你想要做某个类的机会是很小的。somedictionary.add("name","value"),成为一个明智的实现的机会几乎是不存在的。
一般来说,我只是让我的类有一个字典类型的私有成员,并公开一些方法例如
| 1 | public IEnumerable<String> Names { get { return _myDictionary.Keys;} } | 
等。
如果我经常这样做,那就委托给一个简单的班级去做。
是的,因为您没有指定返回类型。
两种可能性:
更好的方法是:指定字典的返回类型
更糟的是:在调用方法中将对象强制转换为字典