Reputation: 15698
Consider a method with the following signature:
void foo(List<T> myList) ...
Let's assume, by using reflection, you need to construct such a function and obtain the PropertyInfo
details of the T
type parameter. Calling typeof(T).GetProperties(...)
should do the trick, so we can add the following line to our method, to obtain these details.
void foo(List<T> myList)
{
PropertyInfo[] props =
typeof(T).GetProperties(BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy);
...
}
This provides the information we need... except when T
is an interface parameter, what I'm finding is that props
only contains the interface properties and not the properties associated with class that is within the list, which inherits from the interface.
To be clear, my interface AND my class definitions are public, as are the properties within my classes.
How can I get the properties associated with the actual type that inherits an interface rather than strictly the interface properties?
Upvotes: 2
Views: 82
Reputation: 149608
If you want to get a flat list of all object properties contained inside the List<T>
, here's a LINQ solution:
IEnumerable<PropertyInfo> properties =
myList.SelectMany(x => x.GetType()
.GetProperties(BindingFlags.Public |
BindingFlags.Instance));
If you need to access the declaring type, you can always look PropertyInfo.DeclaryingType
If you don't want a flat list, Select
can do:
IEnumerable<PropertyInfo[]> properties =
myList.Select(x => x.GetType()
.GetProperties(BindingFlags.Public |
BindingFlags.Instance));
Upvotes: 2
Reputation: 7793
If you want the actual type, you probably need to get it for each item:
foreach (T t in myList)
{
Type itemType = t.GetType();
itemType.GetProperties(...)
// etc.
}
You can also add specific code for different types with:
if(itemType == typeof(MyConcreteType))
{
// do specific stuff for that type
}
Upvotes: 4