Reputation: 1821
Everything is in the title, but let me put some code. Let's say we have a class with 2 methods with the same name:
class MyClass
{
/// <summary>
/// The first version
/// </summary>
public TItem Foo(long param1) { ... }
/// <summary>
/// Overload with a generic parameters
/// </summary>
public bool Foo<TItem>(out TItem item, long param1) { ... }
}
An we need to get the MethodInfo for the second 'Foo' method which has a generic out parameter:
public class AnotherClass
{
public MethodInfo GetFooForType(Type typeOfItem)
{
// the answer is probably GetMethod with the right parameters
return typeof(MyClass).GetMethod(???);
}
}
Please note that:
Upvotes: 1
Views: 1428
Reputation: 142008
If your class is a generic one (and if it is not, your code will give you a warning about overriding) you can use typeof(MyClass<>).GetGenericArguments().First().MakeByRefType()
:
class MyClass<TItem>
{
/// <summary>
/// The first version
/// </summary>
public TItem Foo(long param1) { throw new Exception(); }
/// <summary>
/// Overload with a generic parameters
/// </summary>
public bool Foo(out TItem item, long param1) { throw new Exception();}
}
var genericMI = typeof(MyClass<>).GetMethod(
"Foo",
new[]
{
typeof(MyClass<>).GetGenericArguments().First().MakeByRefType(),
typeof(long)
});
For non-generic you can use Type.MakeGenericMethodParameter(0).MakeByRefType()
(actually it will work with MyClass<T>
and override of generic parameter in Foo<T>
too):
class MyClass
{
/// <summary>
/// The first version
/// </summary>
public int Foo(long param1) { throw new Exception(); }
/// <summary>
/// Overload with a generic parameters
/// </summary>
public bool Foo<TItem>(out TItem item, long param1) { throw new Exception();}
}
var genericMI = typeof(MyClass).GetMethod(
"Foo",
new[]
{
Type.MakeGenericMethodParameter(0).MakeByRefType(),
typeof(long)
});
Upvotes: 3