简体   繁体   中英

C# GetMethod info of Queryable class

I'm new at Reflection and I was trying the below peice of code

var queryableLastMethodInfo = typeof(Queryable).GetMethod("Last", new Type[]{ typeof(IQueryable<>) });

but queryableLastMethodInfo always returns null .

Could you please help?

This should give you the MethodInfo of the "Last" extension method that doesn't take a predicate:

var queryableLastMethodInfo = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
    .FirstOrDefault(x => x.Name == "Last" && x.GetParameters().Count() == 1);

...and this should give you the other one:

var queryableLastMethodInfo = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
    .FirstOrDefault(x => x.Name == "Last" && x.GetParameters().Count() == 2);

You can find all Last methods and select the one with only one parameter:

var method = typeof (Queryable).GetMethods()
                               .Where(m => m.Name == "Last")
                               .First(m => m.GetParameters().Length == 1);

Generic case is described in this question and answer .

Don't take risk code failed if Queryable receuve new methods called "Last" and taking only one parameter.

Accurate is never to much.

var queryableLastMethodInfo = typeof(Queryable).GetMethods().Single(_Method => _Method.Name == "Last" && _Method.IsGenericMethod && _Method.GetGenericArguments().Length == 1 && _Method.GetParameters().Length == 1   && _Method.GetParameters().Single().ParameterType == typeof(IQueryable<>).MakeGenericType(_Method.GetGenericArguments().Single()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM