私のリフレクション方法で正しい値をすべて得ることができません。モデルを横断し始めると、メソッドが、ItemDataクラスに到達したときにIEnumerableが横方向に移動するのを検出しなくなったようです。 (つまり、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; }
私はそれが近くに持っているが、目の別のペアが認識されるであろうと信じています。
または追加 '|| BindingFlags.NonPublic'を呼び出します。 –
@ErikPhilips IMOは別の回答にする必要があります(私はそれをupvote!) - これは、より正確に元のコンテキストでの質問に対処する、私は感じる –
ありがとう、私はこれを含める答えを更新しました。クラスメンバーの範囲を変更するよりも理にかなっています。 :) –