Why is the compiler choosing the wrong method overload?

后端 未结 2 1997
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题