c# - Select Right Generic Method with Reflection -
i want select right generic method via reflection , call it.
usually quite easy. example
var method = typeof(mytype).getmethod("themethod"); var typedmethod = method.makegenericmethod(thetypetoinstantiate);
however issue start when there different generic overloads of method. example static-methods in system.linq.queryable-class. there 2 definitions of 'where'-method
static iqueryable<t> where(this iqueryable<t> source, expression<func<t,bool>> predicate) static iqueryable<t> where(this iqueryable<t> source, expression<func<t,int,bool>> predicate)
this meand getmethod doesn't work, because cannot destiguish two. therefore want select right one.
so far took first or second method, depending on need. this:
var method = typeof (queryable).getmethods().first(m => m.name == "where"); var typedmethod = method.makegenericmethod(thetypetoinstantiate);
however i'm not happy this, because make huge assumption first method right one. rather want find right method argument type. couldn't figure out how.
i tried passing 'types', didn't work.
var method = typeof (queryable).getmethod( "where", bindingflags.static, null, new type[] {typeof (iqueryable<t>), typeof (expression<func<t, bool>>)}, null);
so has idea how can find 'right' generic method via reflection. example right version of 'where'-method on queryable-class?
it can done, it's not pretty!
for example, first overload of where
mentioned in question this:
var where1 = typeof(queryable).getmethods() .where(x => x.name == "where") .select(x => new { m = x, p = x.getparameters() }) .where(x => x.p.length == 2 && x.p[0].parametertype.isgenerictype && x.p[0].parametertype.getgenerictypedefinition() == typeof(iqueryable<>) && x.p[1].parametertype.isgenerictype && x.p[1].parametertype.getgenerictypedefinition() == typeof(expression<>)) .select(x => new { x.m, = x.p[1].parametertype.getgenericarguments() }) .where(x => x.a[0].isgenerictype && x.a[0].getgenerictypedefinition() == typeof(func<,>)) .select(x => new { x.m, = x.a[0].getgenericarguments() }) .where(x => x.a[0].isgenericparameter && x.a[1] == typeof(bool)) .select(x => x.m) .singleordefault();
or if wanted second overload:
var where2 = typeof(queryable).getmethods() .where(x => x.name == "where") .select(x => new { m = x, p = x.getparameters() }) .where(x => x.p.length == 2 && x.p[0].parametertype.isgenerictype && x.p[0].parametertype.getgenerictypedefinition() == typeof(iqueryable<>) && x.p[1].parametertype.isgenerictype && x.p[1].parametertype.getgenerictypedefinition() == typeof(expression<>)) .select(x => new { x.m, = x.p[1].parametertype.getgenericarguments() }) .where(x => x.a[0].isgenerictype && x.a[0].getgenerictypedefinition() == typeof(func<,,>)) .select(x => new { x.m, = x.a[0].getgenericarguments() }) .where(x => x.a[0].isgenericparameter && x.a[1] == typeof(int) && x.a[2] == typeof(bool)) .select(x => x.m) .singleordefault();
Comments
Post a Comment