Reflection a properties of type of generic list

2019-05-31 13:08发布

问题:

i have a class like below

public class Foo<T>
{
  public List<T> Items{ get; set; }
}

and

i have a instance that above class,

Foo<Bar> bars = GetBars();

how i can get properties of Bar using reflection?

i try this

PropertyInfo[] properties = bars.Items.First().GetType().GetProperties();

but i think,its not good way,is there any better way do this?

回答1:

var Properties = bars.GetType().GetGenericArguments()[0].GetProperties();

Assuming you don't know the type the list will contain.

If it'll always be a Bar then use typeof(Bar).GetProperties();



回答2:

try:

var properties = typeof(Bar).GetProperties();