views:

99

answers:

2

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 no public, has dozen overloads, uses generic arguments from base type, not just its immediate interface etc.

+1  A: 

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());
Darren Kopp
A: 

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)

VirtualBlackFox
yeap, that might work, and that's what I'm doing right now. However the performance is far from stellar, hence I'm asking if there's a better way
Krzysztof Koźmic