从 dll C# 更改方法

Change method from dll C#

我在我的解决方案中使用了 avalondock 2.0 dll,我需要在另一个项目中从 DockingManager.cs 更改 IOverlayWindowHost.GetDropAreas 方法。 但是,我不想在源文件中这样做。该方法不是虚拟的,我不能像这样覆盖它

class CustomDockingManager : DockingManager
{
     override IEnumerable<IDropArea> GetDropAreas(LayoutFloatingWindowControl draggingWindow)
     {
          //some changes
     }
}

您需要执行 IL 编织 来更改非虚拟方法。你在这里有很多选择。

  • Mono.Cecil. Check this other Q&A that might give you some direction on how to solve your issue: C# Intercept/change/redirect a method

  • PostSharp. If you just want to add some code before and after some method execution, PostSharp makes it easier than emitting intermediate language by hand. You would do it using an OnMethodBoundaryAspect attribute. See this article to get in touch with method aspects: http://www.postsharp.net/blog/post/Day-4-OnMethodBoundaryAspect

虽然通常不推荐,但您可以使用 C# 功能显式地重新实现接口的单个​​方法,就像这样

class CustomDockingManager : DockingManager, IOverlayWindowHost
{
    IEnumerable<IDropArea> IOverlayWindowHost.GetDropAreas(LayoutFloatingWindowControl draggingWindow)
    {
        // ...
    }
}

请注意,这种方式不能使用基础实现,您必须从头开始编写方法。