samedi 16 septembre 2023

C# Reflection and overloaded Methods: Get Method the compiler would have chosen / "Closest Ancestor"

Given this Situation:

class Wrapper {
   class Base {}
   class A : Base {}
   interface IA {}
   class B : A, IA {}

   void Func(Base param) {}
   void Func(A param) {}
   void Code() 
   {
      var param = new B();
      Func(param); //the compiler picks the "best polymorphism match" or maybe "closest ancestor", which is Func(A param)
   }
}

I don't actually know how the compiler picks the method. I assume it's the "closest ancestor", but I'm aware that this definition has problems itself - When a void Func(IA param) { } is added to the code above, the call Func(param); becomes a compile error CS0121 The call is ambiguous between the following methods or properties: 'Wrapper.Func(A)' and 'Wrapper.Func(IA)'

With Reflection, how would I go about to find the same Func the compiler would have chosen if the Type information had been available at compile time? typeof([Func-param]).IsAssignableFrom(typeof(B)) is true for both function params. typeof(B).IsSubclassOf([Func-param]) is also true for both functions.





Aucun commentaire:

Enregistrer un commentaire