我在反射方法中无法获得所有正确的值。似乎当我开始遍历模型时,该方法在到达 ItemData 类时停止查找要横向的 IEnumerables。(即它只会遍历 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; }
我相信我已经接近了,但另一双眼睛会很感激。
这不起作用的原因是因为您提到的属性不是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...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句