扩展方法将对象属性映射到IDictionary的最有效方法是什么:
使用反射是最好的方法吗?有例子吗?
谢谢Z..。
澄清最新情况
"ParentCompany.BillingAddress"字典键应该是基于属性名称的路径,而不是hierarchy.So类型,如果客户有属性
public Company ParentCompany
,而公司有属性
public Address BillingAddress
,那么键路径应该是
public Company ParentCompany
发布于 2012-06-07 16:21:56
编辑:
public static IDictionary<string, string> GetProperties<T>(this T obj)
where T : class
var properties = obj.GetPropertyList();
return properties.ToDictionary(prop => prop.Item1, prop => prop.Item2);
public static IEnumerable<Tuple<string, string>> GetPropertyList<T>(this T obj)
where T : class
if (obj == null)
throw new ArgumentNullException("obj");
Type t = obj.GetType();
return GetProperties(obj, t, t.Name);
private static IEnumerable<Tuple<string, string>> GetProperties(object obj, Type objType, string propertyPath)
// If atomic property, return property value with path to property
if (objType.IsValueType || objType.Equals(typeof(string)))
return Enumerable.Repeat(Tuple.Create(propertyPath, obj.ToString()), 1);
// Return empty value for null values
if (obj == null)
return Enumerable.Repeat(Tuple.Create(propertyPath, string.Empty), 1);
// Recursively examine properties; add properties to property path
return from prop in objType.GetProperties()
where prop.CanRead && !prop.GetIndexParameters().Any()
let propValue = prop.GetValue(obj, null)