W
Wiktor Zychla [C# MVP]
suppose I have a class
class MyContainter {
List<something1> list1;
List<something2> list2;
...
List<somethingn> listn;
othertype1 otherfield1;
...
othertypek otherfieldk;
}
as you can see there are plenty of generics instantiated with different
types.
what I wish is to use reflection to get a list of fields that are of type
List<anything>:
foreach ( FieldInfo fi in typeof(MyContainter).GetFields() )
{
object val = fi.GetValue( TheInstance );
if ( ???? )
{
}
}
what is the best approach to fill the ???? gap so that I have only all these
List<T> fields passed into the if block?
solutions I think about are:
a) matching the type by name - however this is ugly
b) additional attribute on all List<T> fields - seems unnecessary
what I would like is to use pure reflection. something like:
if ( val is List ) { }
if ( val.GetType().IsSubclassOf( ... ) ) { }
however, none of my tries compile since List<> is a generic type and cannot
be used without instantiation of the generic argument. in other words, I
cannot make generics generic on another level of abstraction.
is it possible at all? right now I tend to think that this is impossible.
[I should mention that in the real-life application there are no List<T>
fields but my_own_generic_class<T,K> so any List<T> specific solutions are
not acceptable]
Thanks in advance,
Wiktor Zychla
class MyContainter {
List<something1> list1;
List<something2> list2;
...
List<somethingn> listn;
othertype1 otherfield1;
...
othertypek otherfieldk;
}
as you can see there are plenty of generics instantiated with different
types.
what I wish is to use reflection to get a list of fields that are of type
List<anything>:
foreach ( FieldInfo fi in typeof(MyContainter).GetFields() )
{
object val = fi.GetValue( TheInstance );
if ( ???? )
{
}
}
what is the best approach to fill the ???? gap so that I have only all these
List<T> fields passed into the if block?
solutions I think about are:
a) matching the type by name - however this is ugly
b) additional attribute on all List<T> fields - seems unnecessary
what I would like is to use pure reflection. something like:
if ( val is List ) { }
if ( val.GetType().IsSubclassOf( ... ) ) { }
however, none of my tries compile since List<> is a generic type and cannot
be used without instantiation of the generic argument. in other words, I
cannot make generics generic on another level of abstraction.
is it possible at all? right now I tend to think that this is impossible.
[I should mention that in the real-life application there are no List<T>
fields but my_own_generic_class<T,K> so any List<T> specific solutions are
not acceptable]
Thanks in advance,
Wiktor Zychla