我在C#.NET 4.0中有一个充满动态对象(Dictionary)的Dictionary。有时值是字符串,int或float,但有时值是ExpandoObject。 Dictionary本身实际上是一个ExpandoObject强制转换为Dictionary以检索其属性。
问题是,我正在迭代主对象的每个属性(因此也是一个Dictionary),当有一个ICollection / IList或ExpandoObject类型的对象时,我想执行一个动作。但问题是,如果在Dictionary中有一个动态对象(ExpandoObject),它会显示为Null。
当我在Visual Studio 2010中调试并打开动态视图时,它会将这些对象列为属性,但当我将相同对象的属性视为键值对(从“词典”视图中查看)时,当此对象包含其他ExpandoObject时,value为“null”。 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?我似乎无法弄明白,并且任何帮助都是有意义的!