1

I've been reading posts on this all day and none of them seem to match the situation I've got closely enough. I have a class with the following methods:

IQueryable<TBusinessContract> Query<TBusinessContract>(
    Expression<Func<TBusinessContract, bool>> condition, params string[] children )
    where TBusinessContract : BusinessContract;

IQueryable<TSubType> Query<TSuperType, TSubType>(
    Expression<Func<TSubType, bool>> condition, params string[] children )
    where TSuperType : BusinessContract
    where TSubType : BusinessContract;

I want to get a MethodInfo for the first one. I've tried a number of different combinations and permutations and I either get null or an ambiguous match exception. I have come up with the following that is working but feels a bit kludgy.

MethodInfo queryMethod = Dal.GetType()
    .GetMethods( BindingFlags.Public | BindingFlags.Instance )
    .Where( mi => mi.Name == "Query" )
    .Where( mi => mi.IsGenericMethod )
    .Where( mi => mi.GetGenericArguments().Length == 1 )
    .SingleOrDefault();

Is this the best I can do or am I missing something? I'm using .NET 4.5.

svick
  • 236,525
  • 50
  • 385
  • 514
Craig W.
  • 17,838
  • 6
  • 49
  • 82
  • I did read that post and even tried his code and it continued to return null for me. Perhaps the more fundamental problem is figuring out how to get the correct argument type. typeof(Expression<>) didn't work, and typeof(Expression>) wouldn't even compile. – Craig W. Mar 28 '13 at 17:13

1 Answers1

1

It seems there are no really good reflection methods for these situations. I think what you do is fine. Written just a little more compact:

MethodInfo queryMethod = Dal.GetType().GetMethods()
    .SingleOrDefault(mi => mi.Name == "Query" &&
    mi.GetGenericArguments().Length == 1);

Even if your type contained non-generic methods also named Query, it looks like GetGenericArguments will behave nicely and return an empty (zero-length) array.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181