2011-03-01 190 views
3

如何遍歷對象的屬性並獲取屬性的值。
我有一個對象,有幾個屬性填充數據。用戶通過提供屬性名稱來指定他想要查看的屬性,並且我需要在對象中搜索屬性並將其值返回給用戶。
我該如何做到這一點?
我寫了下面的代碼來獲取財產,但不能得到該道具的價值:循環遍歷對象屬性

public object FindObject(object OBJ, string PropName) 
    { 
     PropertyInfo[] pi = OBJ.GetType().GetProperties(); 
     for (int i = 0; i < pi.Length; i++) 
     { 
      if (pi[i].PropertyType.Name.Contains(PropName)) 
       return pi[i];//pi[i] is the property the user is searching for, 
          // how can i get its value? 
     } 
     return new object(); 
    } 
+0

可能重複[循環通過一個對象屬性在C#(http://stackoverflow.com/questions/957783/loop-through-an-objects -properties-in-c) – Gabe 2011-03-01 13:13:39

+0

http://stackoverflow.com/q/2737663/310574也可能有重複 – Gabe 2011-03-01 13:14:20

回答

8

嘗試這種(代碼插入內聯):

public object FindObject(object OBJ, string PropName) 
{ 
    PropertyInfo[] pi = OBJ.GetType().GetProperties(); 
    for (int i = 0; i < pi.Length; i++) 
    { 
     if (pi[i].PropertyType.Name.Contains(PropName)) 
     { 
      if (pi[i].CanRead)      //Check that you can read it first 
       return pi[i].GetValue(OBJ, null); //Get the value of the property 
     } 
    } 
    return new object(); 
} 
6

要獲得從PropertyInfo的價值,你叫GetValue :)我懷疑你真的要獲得該物業的名稱類型介意你。我懷疑你想:

if (pi[i].Name == PropName) 
{ 
    return pi[i].GetValue(OBJ, null); 
} 

請注意,你應該確保該屬性不是一個索引,並且是可讀和可訪問等LINQ是過濾事情的好辦法,或者你可以只使用Type.GetProperty使用所需的名稱直接訪問該屬性,而不是循環 - 然後然後執行所有您需要的驗證。

您還應該考慮遵循以下命名約定並使用foreach循環。哦,我可能會返回null或拋出異常,如果無法找到屬性。我看不出如何返回一個新的空對象是一個好主意。

2

pi[i].GetValue(OBJ,null);是使用的功能。

1
public static object FindObject(object obj, string propName) 
{ 
    return obj.GetType().GetProperties() 
     .Where(pi => pi.Name == propName && pi.CanRead) 
     .Select(pi => pi.GetValue(obj, null)) 
     .FirstOrDefault(); 
} 
0

您可以調用PropertyInfo.GetValue方法傳遞對象以獲取其值。

public object FindObject(object OBJ, string PropName)  
{   
    PropertyInfo[] pi = OBJ.GetType().GetProperties();   

    for (int i = 0; i < pi.Length; i++)   
    {    
     if (pi[i].Name == PropName)     
     { 
      return pi[i].GetValue(OBJ, null); 
     } 
    }    

    return new object();  
} 

所有反射類型,包括PropertyInfo都綁定到該類。您必須傳遞該類的實例才能獲取任何與實例相關的數據。