【发布时间】:2017-11-13 19:13:09
【问题描述】:
我需要帮助通过继承对动态对象属性进行排序。
我有一个应该创建 ExpandoObject 的方法。我遇到了重复问题,因为“obj.GetType().GetProperties()”获取所有属性,而与用于隐藏属性的“new”关键字无关(请注意,baseproperty 是从其他项目继承的)。
我的解决方案是在继承级别之后对所有属性进行排序,并优先化最高派生类中的属性。基类应该是最低优先级。
这可能吗?看第二个coden-p就明白我的意思了。
可选的额外信息: 我的方法中的参数对象“obj”属于我的类“UserEditModel”,请参见下面的继承。 “UserEditModel”派生自“UserModel”, “UserModel”派生自“Otherproject.UserModel”, “Otherproject.UserModel”派生自“Otherproject.PageModelBase”
我现在的代码:
public static dynamic ToExpando(this object obj)
{
if (obj is ExpandoObject || obj is LenientExpandoObject)
return obj;
var result = new ExpandoObject();
var d = result as IDictionary<string, object>;
var instanceProps = obj.GetType().GetProperties();
//Add all properties except baseclass properties
var excludeBaseClassProp = obj.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
foreach (var excludeBaseClassPropItem in excludeBaseClassProp)
{
d.Add(excludeBaseClassPropItem.Name, excludeBaseClassPropItem.GetValue(obj, null));
}
//Add the rest of the properties and prevent duplicates
foreach (var item in instanceProps)
{
if (d.AsEnumerable().Any(p => p.Key.Contains(item.Name)))
continue;
d.Add(item.Name, item.GetValue(obj, null));
}
return result;
}
我想做的事:
public static dynamic hannes(this object obj)
{
if (obj is ExpandoObject || obj is LenientExpandoObject)
return obj;
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
var props = obj.GetType().GetProperties();
foreach (var item in props.OrderBy(prop => prop.INHERITANCE_LEVEL)) //<-----WHAT I WANT TO DO!
{
d.Add(item.Name, item.GetValue(obj, null));
}
return result;
}
【问题讨论】:
-
type.GetProperties(System.Reflection.BindingFlags.DeclaredOnly)不包括继承的属性。type.BaseType返回“当前类型直接继承的类型”。递归或循环,一切就绪。