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.
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());
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With