我想知道如何获取C#中的属性值,但此属性是另一个类型。C#关于一个类的嵌套属性的思考
public class Customer
{
public string Name {get; set;}
public string Lastname {get; set;}
public CustomerAddress Address {get; set;}
}
所以我能够得到的名称和姓氏的属性值,但我挺不明白如何让CustomerAddress.City的价值。
这是我到现在为止。
public object GetPropertyValue(object obj, string property)
{
if (string.IsNullOrEmpty(property))
return new object { };
PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
然后在LINQ语句中使用这个方法。
var cells = (from m in model
select new
{
i = GetPropertyValue(m, key),
cell = from c in columns
select reflection.GetPropertyValue(m, c)
}).ToArray();
所以我没有得到CustomerAddress的价值。
任何帮助将深表谢意。
**** ****更新
我这里怎么设法做到这一点。
public object GetNestedPropertyValue(object obj, string property)
{
if (string.IsNullOrEmpty(property))
return string.Empty;
var propertyNames = property.Split('.');
foreach (var p in propertyNames)
{
if (obj == null)
return string.Empty;
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(p);
if (info == null)
return string.Empty;
obj = info.GetValue(obj, null);
}
return obj;
}
如何设置一个嵌套属性的值? (与此相同,但对于info.SetValue ...)? – Denis 2011-08-11 23:12:44