2010-09-08 82 views
2

我想知道如何获取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; 
     } 
+0

如何设置一个嵌套属性的值? (与此相同,但对于info.SetValue ...)? – Denis 2011-08-11 23:12:44

回答

3

首先,如果你想得到CustomerAddress.City的值,你永远不会得到它。 CustomerAddress是类型,而不是属性名称。你想得到Address.City

也就是说,你的GetPropertyValue没有设置做你想做的。

尝试分裂名由点:

var propertyNames = property.split('.');

现在,你有属性名称{"Address", "City"}

列表然后,您可以通过这些属性名称循环,一个接一个,递归地呼叫GetPropertyValue

应该这样做:)

+0

谢谢你解决了这个问题,我没有想到递归。 – 2010-09-08 19:16:00

0

@迈克尔 - >反转部分;-)

public static void SetNestedPropertyValue(object obj, string property,object value) 
     { 
      if (obj == null) 
       throw new ArgumentNullException("obj"); 

      if (string.IsNullOrEmpty(property)) 
       throw new ArgumentNullException("property"); 

      var propertyNames = property.Split('.'); 

      foreach (var p in propertyNames) 
      { 

       Type type = obj.GetType(); 
       PropertyInfo info = type.GetProperty(p); 
       if (info != null) 
       { 
        info.SetValue(obj, value); 
        return; 
       } 

      } 

      throw new KeyNotFoundException("Nested property could not be found."); 
     } 
+0

这完全没用,它甚至没有一个简单的Typeconversion。它也不会创建父对象的新实例。在第二次迭代中将会有一个null参考。这根本不起作用,只适用于字符串,并且只适用于不是复杂类型的情况。 – 2018-01-29 14:13:53