下面的代码片段的foreach语句中有以下异常:
exception:System.InvalidCastException:不能从源类型转换到目标类型。
我仔细观察了一下LitJson.JsonData。它确实有internal class OrderedDictionaryEnumerator : IDictionaryEnumerator实现。我不知道缺了什么。有什么想法吗?
protected static IDictionary<string, object> JsonToDictionary(JsonData in_jsonObj)
{
foreach (KeyValuePair<string, JsonData> child in in_jsonObj)
{
...
}
}发布于 2015-05-19 00:47:57
LitJson.JsonData类声明为:
public class JsonData : IJsonWrapper, IEquatable<JsonData>而IJsonWrapper则来自于这两个接口:System.Collections.IList和System.Collections.Specialized.IOrderedDictionary。
请注意,这两个版本都是非泛型集合版本。枚举时,结果不会得到一个KeyValuePair<>。相反,它将是一个System.Collections.DictionaryEntry实例。
因此,您必须将foreach更改为:
foreach (DictionaryEntry child in in_jsonObj)
{
// access to key
object key = child.Key;
// access to value
object value = child.Value;
...
// or, if you know the types:
var key = child.Key as string;
var value = child.Values as JsonData;
}https://stackoverflow.com/questions/30314637
复制相似问题