2012-12-28 40 views
0

我有一個列表,ProductSpec {id, Name}另一份爲Product {productspec, id, Name}。 當我嘗試接入產品的性能到列表在列表的PropertyInfo獲取屬性迭代

IList<PropertyInfo> properties = typeof(Product).GetProperties().ToList(); 

我retreving我的ID和名稱這是很好的,但是當我嘗試重申一個productspec作爲

foreach(var property in properties) 
{ 
    IList<PropertyInfo> properties = property.propertytype.getproperties(); 
    // I am not getting the productspec columns 
    //instead I am getting (capacity,count) as my properties.. 
} 

所以,我該怎麼辦屬性從列表中重申列表來獲取列表屬性

+2

這是什麼'property.propertytypr.getproperties()'? – V4Vendetta

+0

對不起,我編輯我的問題,它應該是屬性類型 – Bhuvan

+0

你能張貼'Product'和'ProductSpec'類的定義,以幫助我們更好地回答你的問題嗎? – jam40jeff

回答

3

是對ProductSpec類型的Product類類型ProductSpecList<ProductSpec>類型的?如果它是一個列表,你可以做以下事情:

var properties = new List<PropertyInfo>(); 
foreach (var property in properties) 
{ 
    if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType) 
     && property.PropertyType.IsGenericType 
     && property.PropertyType.GetGenericArguments().Length == 1) 
    { 
     IList<PropertyInfo> innerProperties = property.PropertyType.GetGenericArguments()[0].GetProperties(); 
     //should contain properties of elements in lists 
    } 
    else 
    { 
     IList<PropertyInfo> innerProperties = property.PropertyType.GetProperties(); 
     //should contain properties of elements not in a list 
    } 
} 
+0

@lazyberezovsky在回答「問題是在錯誤的代碼(在編輯中修復)和變量名,這與foreach中的變量衝突。「我已經承認,原始代碼包含會導致它不能編譯的錯誤。然而,在評論中,提問者陳述他看到的結果,表明他沒有粘貼他正在運行的實際代碼(這是可編譯的)。這些結果表明他的財產實際上可能是'List '而不是'ProductSpec'類型。 – jam40jeff

+1

@lazyberezovsky但是,由於問題沒有說清楚,我將刪除你的downvote並對問題應用downvote(如果他進一步澄清或至少給我們編譯代碼,我將刪除它)。 – jam40jeff

+0

「由於問題沒有說清楚」完全同意你,也刪除downvote –

3

您需要使用相同的代碼屬性類型:

var innerProperties = property.PropertyType.GetProperties().ToList(); 

而且重命名結果 - 其與變量foreach循環衝突。

+0

當我這樣做,我不能夠retevie id和產品規格的名稱...我retreivng一些其他屬性,,, – Bhuvan

+0

@Bhuvan一些其他產品會員,那麼你越來越性能,或'productspec'財產沒有類型,你期望它應該有。驗證'productspec'屬性的類型。驗證它是公共財產。還要設置一個斷點並驗證您正在獲取結果的屬性的名稱。 –

+1

你是對的......我是從我的腦海......當我一個小時後,看到我的代碼謝謝 – Bhuvan

0

試試這個:

PropertyInfo[] propertyInfos = typeof(Product).GetProperties(); 
     foreach (var propertyInfo in propertyInfos) 
     { 
      var inner = propertyInfo.PropertyType.GetProperties().ToList(); 
     } 

public class Product 
{ 
    public ProductSpec Spec { get; set; } 

    public string Id { get; set; } 

    public string Name { get; set; } 
} 

public class ProductSpec 
{ 
    public string Id { get; set; } 

    public string Name { get; set; } 
}