2013-04-16 99 views
5

我有一個嵌套的對象集,即一些屬性是自定義對象。我希望在屬性名稱中使用字符串來獲取層次結構組中的對象屬性值,並使用某種形式的「find」方法來掃描層次結構以查找具有匹配名稱的屬性,並獲取其值。如何使用字符串作爲屬性名稱從嵌套對象組中找到對象屬性值?

這是可能的,如果是的話如何?

非常感謝。

編輯

類定義可能是僞代碼:

Class Car 
    Public Window myWindow() 
    Public Door myDoor() 
Class Window 
    Public Shape() 
Class Door 
    Public Material() 

Car myCar = new Car() 
myCar.myWindow.Shape ="Round" 
myDoor.Material = "Metal" 

都有點做作,但通過使用魔法字符串「形」我能「找到」的「形」屬性的值在某種形式的查找函數中,從頂層對象開始。 ie:

string myResult = myCar.FindPropertyValue("Shape") 

希望myResult =「Round」。

這就是我所追求的。

謝謝。

+1

試圖獲得更具體的使用 –

+1

反射和'PropertyInfo' http://stackoverflow.com/questions/1355090/using-propertyinfo-getvalue –

+0

只是添加了例如編輯。這是否改變了思考的答案?應對嵌套很重要。 – SamJolly

回答

9

根據您在問題中顯示的類,您需要遞歸調用來迭代對象屬性。怎麼樣東西,你可以重複使用:

object GetValueFromClassProperty(string propname, object instance) 
{ 
    var type = instance.GetType(); 
    foreach (var property in type.GetProperties()) 
    { 
     var value = property.GetValue(instance, null); 
     if (property.PropertyType.FullName != "System.String" 
      && !property.PropertyType.IsPrimitive) 
     { 
      return GetValueFromClassProperty(propname, value); 
     } 
     else if (property.Name == propname) 
     { 
      return value; 
     } 
    } 

    // if you reach this point then the property does not exists 
    return null; 
} 

propname是您正在搜索的屬性。您可以使用是這樣的:

var val = GetValueFromClassProperty("Shape", myCar); 
4

是的,這是可能的。

public static Object GetPropValue(this Object obj, String name) { 
    foreach (String part in name.Split('.')) { 
     if (obj == null) { return null; } 

     Type type = obj.GetType(); 
     PropertyInfo info = type.GetProperty(part); 
     if (info == null) { return null; } 

     obj = info.GetValue(obj, null); 
    } 
    return obj; 
} 

public static T GetPropValue<T>(this Object obj, String name) { 
    Object retval = GetPropValue(obj, name); 
    if (retval == null) { return default(T); } 

    // throws InvalidCastException if types are incompatible 
    return (T) retval; 
} 

要使用此:

DateTime now = DateTime.Now; 
int min = GetPropValue<int>(now, "TimeOfDay.Minutes"); 
int hrs = now.GetPropValue<int>("TimeOfDay.Hours"); 

看到這個link,供大家參考。

+0

謝謝你。這是否意味着我必須在「名稱」中指定對象層次結構。我希望只指定「Shape」,它會搜索對象層次結構以查找名字匹配。 – SamJolly

+0

是的。請注意,您不能在類上擁有重複的屬性,因此如果您對層次結構持懷疑態度,這不會成爲問題。 – lexeRoy

相關問題