【发布时间】:2015-11-25 04:27:36
【问题描述】:
我正在尝试构建一个通用方法来将对象转换为 ExpandoObjects,并且我可以处理所有情况,除非其中一个属性是数组。
public static ExpandoObject ToExpando(this object AnonymousObject) {
dynamic NewExpando = new ExpandoObject();
foreach (var Property in AnonymousObject.GetType().GetProperties()) {
dynamic Value;
if (IsPrimitive(Property.PropertyType)) {
Value = Property.GetValue(AnonymousObject);
} else if (Property.PropertyType.IsArray) {
dynamic ArrayProperty = new List<dynamic>();
var ArrayElements = (Array)Property.GetValue(AnonymousObject);
for (var i = 0; i < ArrayElements.Length; i++) {
var Element = ArrayElements.GetValue(i);
if (IsPrimitive(Element.GetType())) {
ArrayProperty.Add(Element);
} else {
ArrayProperty.Add(ToExpando(Element));
}
}
Value = ArrayProperty;//.ToArray();
} else {
Value = ToExpando(Property.GetValue(AnonymousObject));
}
((IDictionary<string, object>) NewExpando)[Property.Name] = Value;
}
return NewExpando;
}
private static bool IsPrimitive(System.Type type) {
while (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>)) {
// nullable type, check if the nested type is simple.
type = type.GetGenericArguments()[0];
}
return type.IsPrimitive || type.IsEnum || type.Equals(typeof (string)) || type.Equals(typeof (decimal));
}
任何作为数组的属性似乎都不是动态对象,当我在剃须刀模板之类的东西上使用它时,数组元素和属性不可见。
例如,如果我这样做:
var EmailParams = new {
Parent = new {
Username = "User1",
},
Students = new [] {new {Username = "Student1", Password = "Pass1"} }
};
如您所见,顶部的匿名对象有一个学生数组,但转换后的 ExpandoObject 没有。
有没有人知道我将如何更改代码以在 ExpandoObject 中添加对数组/列表的支持?
谢谢!
【问题讨论】:
-
也许你需要这个项目:github.com/chsword/jdynamic
标签: c# .net expandoobject