c# - Get OrderBy method using reflection -
i want implement generic pager , filter view model project , i'm stuck on getting orderby method using reflection. here i've tried, keep getting null
methodinfo
. seems i'm passing wrong type[]
arguments getmethod()
method, can't right.
protected virtual expression<func<t, icomparable>> getorderbyexpression() { var type = typeof(t); var property = type.getproperty("datasetname"); var parameter = expression.parameter(type, "x"); var propertyaccess = expression.makememberaccess(parameter, property); var orderbyexp = expression.lambda(propertyaccess, parameter); var methodinfo = typeof(enumerable).getmethod("orderby", new type[] { orderbyexp.body.type }); var predicatebody = expression.call(propertyaccess, methodinfo, orderbyexp); var expression = expression.lambda<func<t, icomparable>>(predicatebody, parameter); return expression; }
then enumerable.orderby
extension method static method have use overload getmethod
can specify bindingflags
(bindingflags.static | bindingflags.public
instead of default bindingflags.instance | bindingflags.public
).
you have specify 2 parameters method - syntactically looks there 1 parameter because extension method there second parameter have specify.
this method want via reflection:
public static iorderedenumerable<tsource> orderby<tsource, tkey>( ienumerable<tsource> source, func<tsource, tkey> keyselector )
you need 2 parameter types:
var sourcetype = typeof(ienumerable<>).makegenerictype(type); var keyselectortype = orderbyexp.compile().gettype();
it seems way specific overload of method generic parameters have perform search. fortunately, there 2 overloads of enumerable.orderby
, 1 want 1 2 parameters:
var genericmethodinfo = typeof(enumerable) .getmethods(bindingflags.static | bindingflags.public) .first(mi => mi.name == "orderby" && mi.getparameters().length == 2); var methodinfo = genericmethodinfo.makegenericmethod(sourcetype, keyselectortype);
this returns desired methodinfo
, have modify remaining 2 lines of code because method static method , have specify null instance in expression.call
.
Comments
Post a Comment