Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get generic method on closed generic type, having open MethodInfo from open generic type?

Imagine type like this (C#):

public interface IAmGeneric<T>
{
   void SoAmI<T1>(T one, T1 two);
}

Given I have open generic MethodInfo from open generic version of the type (IAmGeneric<>.SoAmI<>()) and the following array

new[] { typeof(int), typeof(string) }'

I'm looking for well performing and reliable way of getting closed version of the MethodInfo like this:

IAmGeneric<int>.SoAmI<string>()

UPDATE:

by reliable I mean it should handle cases when the method is not public, has dozen overloads, uses generic arguments from base type, not just its immediate interface etc.

like image 376
Krzysztof Kozmic Avatar asked Sep 24 '10 23:09

Krzysztof Kozmic


2 Answers

Something like so? Not sure exactly what you are looking for, maybe expand on your question... This definitely would need some checks added (like checking if declaring type is generic / if method is generic, etc)

var method = typeof(IAmGeneric<>).GetMethod("SoAmI");
var types = new[] { typeof(int), typeof(string) };


var methodTypeParams = method.GetGenericArguments();
var fullType = method.DeclaringType.MakeGenericType(types.Take(types.Length - methodTypeParams.Length).ToArray());
var fullMethod = fullType.GetMethod(method.Name).MakeGenericMethod(types.Skip(types.Length - methodTypeParams.Length).ToArray());
like image 155
Darren Kopp Avatar answered Nov 04 '22 02:11

Darren Kopp


Here is a case that is pretty complex to get right:

public interface IAmGeneric<T>
{
    void SoAmI<T1, T2>(T one, T1 two, T2 three);
    void SoAmI<T1, T2>(T one, T2 two, T1 three);
    void SoAmI<T1, T2>(T1 one, T two, T2 three);
    void SoAmI<T1, T2>(T2 one, T1 two, T three);
    void SoAmI<T1, T2, T3>(T2 one, T1 two, T3 three);
}

For me the solution is to use GetMethods(...).Select() and compare method name, parameter count, types and type parameters count to find the right method (basically everything that is part of the signature of the method).

like image 33
Julien Roncaglia Avatar answered Nov 04 '22 02:11

Julien Roncaglia