1

我有一个在 C# .NET 4.0 中充满动态对象(字典)的字典。有时值是字符串、int 或浮点数,但有时值是 ExpandoObject。Dictionary 本身实际上是转换为 Dictionary 以检索其属性的 ExpandoObject。

问题是,我正在迭代主对象的每个属性(因此也是字典),当有一个 ICollection/IList 或 ExpandoObject 类型的对象时,我想执行一个操作。然而问题是,如果字典中有一个动态对象 (ExpandoObject),它会显示为 Null。

当我在 Visual Studio 2010 中调试并打开动态视图时,它会将这些对象列为属性,但是当我将相同对象的属性作为键值对查看时(从字典视图中查看),值为“ null" 当此对象包含其他 ExpandoObjects 时。Null 永远不会检查为 Collection/EpandoObject 因此我的条件失败。

在使用 ExpandoObjects 之前我没有遇到过这个错误,所以我很好奇为什么它将 ExpandoObjects 视为空值。

//Function gets a List of ExpandoObjects (casting it as IDictionary)
    private static dynamic mergeIdObjects(List<IDictionary<string, dynamic>> objects)
    {          
        // Take first object as placeholder for the other objects
        IDictionary<string, dynamic> merged = (objects.First())[ParentObject];

        // For all objects to merge (except first one, already used that one as a placeholder)
        foreach (var o in objects.Skip(1))
        {
            IDictionary<string, dynamic> obj = o[ParentObject];
            // For all keys(property names) in the object)
            foreach (dynamic key in obj.Keys)
            {
                dynamic oldValue;

                // This is where the program doesn't function as it should.
                if (merged.TryGetValue(key, out oldValue)) // If key is already in merged object
                {
        // This never evaluates to True since the IList properties are now 'Null' and they shouldn't!
                    if (oldValue is IList<dynamic>) // If value is a list
                        merged[key].Add(obj[key]);  // then add item to this list
                    else
                        if (merged[key] != obj[key])   // Else create a list and add the item
                            merged[key] = new List<dynamic> { oldValue, obj[key] };
                }
                else
                    merged.Add(key, obj[key]);  // If this key is not in the merged object, add it to the merged object
            }
        }
        IDictionary<string, dynamic> placeHolder = new ExpandoObject();
        placeHolder.Add(ParentObject, merged);

        return (dynamic)placeHolder;
    }

有没有我遗漏的东西,我错过的演员或者使用了错误的 DataType?我似乎无法弄清楚,请提供任何帮助!

4

0 回答 0