Why is the compiler choosing the wrong method overload?

后端 未结 2 1964
遇见更好的自我
遇见更好的自我 2021-01-19 06:29

I have this simple method:

public void CacheDelegate(Object obj, MemberInfo memberInfo)
{
   switch (memberInfo.MemberType)
   {
    case MemberTypes.Field:
         


        
相关标签:
2条回答
  • 2021-01-19 07:01

    Overload resolution works as follows.

    Starting with the type called on, find the set of methods declared on that type that can be used.

    If that set is empty, then try the same with the base type or interfaces declared. Keep moving up the hierarchy until at least one method that matches is found, or else error.

    Of the set that is found, use the most specific method. Error if it's a tie.

    So, of the four methods, three were declared in this class. Of those three two are not applicable. That leaves only public void CacheDelegate(Object obj, MemberInfo memberInfo) as clearly the correct class to call, so it is called.

    You could use ((BaseType)this).CacheDelegate(obj, methodInfo); to force the call you want, since the base type has only one CacheDelegate overload to choose between.

    0 讨论(0)
  • 2021-01-19 07:04

    Jon Hanna already explained why this is happening, I'll just add on by providing the source spec where you can read the details: https://msdn.microsoft.com/en-us/library/aa691336(v=vs.71).aspx

    Here's a few ways you can solve your issue:

    • Don't override or overload that method, use a different name.
    • Don't override that method, overload using different parameters, like adding object ignoreMe. This will force the overload to be compatible, however most will agree it's far from elegant.
    • Instead of overriding, hide the method using new. I'm not 100% sure how overload resolution works when method hiding is involved, but it should cause it to use the correct method. Keep in mind that doing this will of course remove it's polymorphism.
    • Use reflection to manually find the correct overload, and invoke it. This is the messiest one, and also has the most overhead. This may or may not be a problem, depending on your situation. However it's the only solution that retains full polymorphism, if you really want to use that exact override / overload combo.
    0 讨论(0)
提交回复
热议问题