mardi 26 mai 2020

How to resolve generic method ambiguity in C# reflection

I have two generic method overrides, that differ by the number of generic type parameters and argument type

// Argument types
public class Bar<T> {}
public class Bar<T, U> {}

// Generic method overrides
private static void Foo<T> (Bar<T> b) {}
private static void Foo<T, U> (Bar<T, U> b) {}

I'm assuming that i can get the method info for either one by using the appropriate number of type parameters

BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Static;

// Should give Foo<int>
GetType ().GetMethod ("Foo", Flags).MakeGenericMethod (typeof(int));

// Should give Foo<int, int>
GetType ().GetMethod ("Foo", Flags | BindingFlags.Static).MakeGenericMethod (typeof(int), typeof(int));

However this fails with System.Reflection.AmbiguousMatchException.

I tried specifying things like new Type[] {typeof (Bar<,>)} as the types argument for some of the GetMethod overrides, but the result was always null. I know i can workaround the ambiguity simply by using different names for the functions, but i'm interested to know if there's an actual solution to this.

I'm on .NET standard 2.0





Aucun commentaire:

Enregistrer un commentaire