Is there a way to navigate to real implementation of method behind an interface?

后端 未结 15 1464
攒了一身酷
攒了一身酷 2020-12-07 08:58

In Visual Studio, when you right-click a method call, you go to the implementation of that method inside a class except if you access this method through an interface: in th

相关标签:
15条回答
  • 2020-12-07 09:46

    This is not possible. What you are describing would make sense only if the interface would be limited to 1 implementation.

    Consider this example:

    interface IWrite 
    { 
     void Write(); 
    }
    class A : IWrite { 
      public void Write() { Console.WriteLine("A"); } 
    }
    class B : IWrite { 
      public void Write() { Console.WriteLine("B"); } 
    }
    class X : IWrite { 
      private readonly string _x;
      public X(string x) {
        _x = x;
      } 
      public void Write() { Console.WriteLine(_x); } 
    }
    
    class UseIWrite()
    {
      public void Use(IWrite iwrite) 
      {
         iwrite.Write();
      }
    }
    

    If you use go to implementation of Write in UseIWrite, it takes you to the declaration of the interface, because at that point any of the IWrite implementations could be passed into the method.

    Thankfully some tools like for example ReSharper offer you to find all usages of the method, so you can easily navigate to the desired implementation.

    0 讨论(0)
  • 2020-12-07 09:46

    Check out this new free Visual Studio 2013 Extension - Implementator. It adds option "Go to implementation" to Visual Studio editor context menu.

    It is not so reliably and fast as Resharper, but does it's job just fine.

    0 讨论(0)
  • 2020-12-07 09:47

    Going to the declaration will open up the interface method. Going to the implementation, will take you, or list for you, the classes that implement the code for that interface method (not the interface method itself).

    Update

    As Jon Skeet pointed out in the comments (and I missed before answering), the feature I've described might be a ReSharper feature...not a Visual Studio one.

    0 讨论(0)
  • 2020-12-07 09:49

    You can try Ctrl + F12 shortcut. It will lead you to implementation just like it will lead you to non interface methods using F12. [I tried it in VS 2017, not sure about other versions ]

    0 讨论(0)
  • 2020-12-07 09:52

    Right-click then "Find All References".

    This will display the line of code for all the places where the method is used including the interface declaration and implementations of the interface method. You can then click on the line to jump to the code location.

    0 讨论(0)
  • 2020-12-07 09:53

    Visual Studio with Update 1 now implements this feature! Just right click the member and you should see "Go to implementation" right under "Go to definition".

    0 讨论(0)
提交回复
热议问题