C# 添加监听器到外部 API 属性

问题描述 投票:0回答:1

我正在使用该工具的插件 API 为该工具编写一个插件。该 API 为重要事件(例如创建或修改的对象)提供了多个回调。然而,不幸的是,这个 API 看起来不太一致,因此对于我需要监听的某些属性,该事件不会触发。

有没有一种方法可以在不直接代码访问的情况下向 API 外部类的属性或方法添加侦听器?我知道类可以扩展,但我不知道更改现有属性。

API 是闭源的,所以我在这里真的无能为力。开发人员似乎不再支持他们的 API,因此他们实现这些更改的希望很小,因此我必须寻找解决方法。如果可能的话,我很高兴能提供有关如何实现这一目标的任何示例。

我想要完成的伪代码示例:

public class ApiClass // the class I have no access to
{
     public string SomeProperty { get; set; } // this property is set via the tool's interface, this event I want to hook into
}

public class MyClass // my code
{
    private Listener myPropListener = new Listener();

    public void init(ApiClass obj)
    {
        obj.SomeProperty.AddListener(myPropListener);
    }
}

我不确定包装 API 类有何好处,因为该工具仍在其自己的模型(例如 API 类)上运行,并且不使用我要编写的任何包装器。

c# external event-listener
1个回答
1
投票

我发现这篇文章描述了创建动态代理来包装对象实例并拦截方法调用,然后使用DynamicObject.TryInvokeMember转发它们。

这样做有很多缺点,例如对象是动态,所以智能感知就被抛到了窗外,它通过反射调用所有东西,这会产生开销。

但是如果它把你从洞里挖出来......

© www.soinside.com 2019 - 2024. All rights reserved.