【发布时间】:2011-04-09 19:26:45
【问题描述】:
我想知道如何在 C# 中获取属性的值,但是这个属性是另一种类型。
public class Customer
{
public string Name {get; set;}
public string Lastname {get; set;}
public CustomerAddress Address {get; set;}
}
所以我能够获取 Name 和 LastName 的属性值,但我完全不知道如何获取 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...)?
标签: c# linq linq-to-sql reflection properties