簡體   English   中英

foreach循環中的Unity LitJson.JsonData異常

[英]Unity LitJson.JsonData exception on cast in foreach loop

我的以下代碼段的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)
    {
        ...
    }
}

LitJson.JsonData類聲明為:

public class JsonData : IJsonWrapper, IEquatable<JsonData>

IJsonWrapper依次從這兩個接口派生: System.Collections.IListSystem.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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM