c# - How to find out if a type implements generics base class -
using example below... how can find out whether property of type implementing generics class foo?
public class foo<tbaz> { } public class bar { public foo<int> fooint { get; set; } public foo<string> foostring { get; set; } public double someother { get; set; } public int getfoocount() { return typeof(bar).getproperties().where(p => p.gettype().isgenerictype).count(); } }
if wanted find foo<int>
, easy, how can find out if contains foo<int>
, foo<double>
etc...?
i have written bit of getfoocount() have far...
thanks
return typeof(bar).getproperties().where(p => p.propertytype.isgenerictype && p.propertytype.getgenerictypedefinition() == typeof(foo<>)).count();
note: won't automatically work class nongenericsubtype : foo<blah> {...}
, nor work class genericsubtype<t> : foo<t> {...}
- if need handle those, gets more fun.
for more general case, need uses recursion on type:
public static int getfoocount() { return typeof(bar).getproperties() .count(p => getfootype(p.propertytype) != null); } private static type getfootype(type type) { while(type != null) { if (type.isgenerictype && type.getgenerictypedefinition() == typeof(foo<>)) return type.getgenericarguments()[0]; type = type.basetype; } return null; }
note answers "now how find t
?"
Comments
Post a Comment