2017-04-18 11 views
1

私のリフレクション方法で正しい値をすべて得ることができません。モデルを横断し始めると、メソッドが、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; } 

私はそれが近くに持っているが、目の別のペアが認識されるであろうと信じています。

答えて

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

ありがとう、私はこれを含める答えを更新しました。クラスメンバーの範囲を変更するよりも理にかなっています。 :) –

関連する問題