2017-04-18 96 views
1

我无法在我的反射方法中获取所有正确的值。看起来,当我开始横穿模型时,该方法只是停止找到IEnumerables横切到ItemData类时。 (即它只会遍历ItemId和Active,但不会将IEnumerables识别为属性)使用泛型类型的反射属性名称

我需要做的是在整个类型中获取各种IEnumerables的名称。例如,当类型通过代码传递时,以下项目将被添加到列表:Content,Data,ItemAttributes,ItemUrls和InventoryInformation。

型号:

public class ModelBase<TModel> 
{ 
    public string Error { get; set; } 
    public IEnumerable<TModel> Content { get; set; } 
} 

public class ItemContent 
{ 
    public IEnumerable<ItemData> Data { get; set; } 
    public int Total { get; set; } 
} 

public class ItemData 
{ 
    public long ItemId { get; set; } 
    public bool Active { get; set; } 
    IEnumerable<ItemAttribute> ItemAttributes { get; set; } 
    IEnumerable<string> ItemUrls { get; set; } 
    IEnumerable<InventoryInformation> InventoryInformation { get; set; } 
} 

public class ItemAttribute 
{ 
    public string AttributeName { get; set; } 
    public bool IsRequired { get; set; } 
} 

public class InventoryInformation 
{ 
    public int AreaId { get; set; } 
    public double Price { get; set; } 
} 

验证码:

// T is ModelBase<TModel> in this context... 
// TModel is ItemContent in this context... 
GetProperties(typeof(T)); 

private void GetProperties(Type classType) 
{ 
    foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) 
    { 
     if (property.PropertyType.IsGenericType && (property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>))) 
     { 
      ValuesToList.Add(property.Name); 

      foreach (Type nestedType in property.PropertyType.GetGenericArguments()) 
      { 
       GetProperties(nestedType); 
      } 
     } 
    } 
} 

private List<string> ValuesToList { get; set; } 

我相信我有它关闭,但另一双眼睛将不胜感激。

回答

3

这不起作用的原因是因为您提到的属性不是public,并且您没有设置绑定标记BindingFlags.NonPublic。得到这个工作

的一种方法,那么,将它们设置为public

public class ItemData 
{ 
    public long ItemId { get; set; } 
    public bool Active { get; set; } 

    public IEnumerable<ItemAttribute> ItemAttributes { get; set; } 
    public IEnumerable<string> ItemUrls { get; set; } 
    public IEnumerable<InventoryInformation> InventoryInformation { get; set; } 
} 

或者,您可以添加BindingFlags.NonPublic到你的绑定标志:

private static void GetProperties(Type classType) 
{ 
    foreach (PropertyInfo property in classType.GetProperties(
     BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)) 
    { 
     // other code omitted... 
+1

或者添加'|| BindingFlags.NonPublic'。 –

+0

@ErikPhilips IMO应该是一个单独的答案(我会upvote它!) - 它更正确地解决了原始上下文中的问题,我感觉 –

+0

谢谢,我已经更新了包含此答案的答案。它确实比改变班级成员的范围更有意义。 :) –