Consider the following code:
public static class FooHelpers
{
public static void Foo(int bar)
{
//...
}
public static void Foo(uint bar)
{
//...
}
public static void Foo(long bar)
{
//...
}
public static void Foo(ulong bar)
{
//...
}
}
Now I have some reflection code that is given a type and checks to see if there exists a Foo method with a parameter of the given type. If there does not exist such a Foo method, my program needs to skip a step. Here is a method to accomplish this:
public static MethodInfo GetFooMethodIfExists(Type parameterType)
{
return typeof(FooHelpers).GetMethod("Foo", new Type[] { parameterType });
}
Seems like a reasonable solution, no? According to the documentation on Type.GetMethod(string name, Type[] types):
// Returns:
// A System.Reflection.MethodInfo object representing the public method whose
// parameters match the specified argument types, if found; otherwise, null.
Now, let's try the following:
MethodInfo m = GetFooMethodIfExists(typeof(short));
Instead of returning null, it returned the method with the int parameter. I just finished a reflection-heavy project that relied on the output of Type.GetMethod(string name, Type[] types) to behave as the documentation states, and it's causing a lot of issues.
Can anyone please tell me why this is happening and/or explain a different way of doing this?
BindingFlags.ExactBinding will fix your problem. Basically, it forces reflection to be strict regarding parameter types. Here is how you can fix your method to use this flag:
public static MethodInfo GetFooMethodIfExists(Type parameterType)
{
return typeof (FooHelpers).GetMethod(
"Foo",
BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding,
(Binder) null,
new[] {parameterType},
(ParameterModifier[]) null);
}
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