动态方法调用
我有两个简单的类:
public class A
{
public void DoSomething();
}
public class Listener
{
public void OnDoSomethingCalled();
}
我希望每次调用 A.DoSomething() 时自动调用 Listener.OnDoSomethingCalled() 。我想在不更改 A 类的情况下执行此操作。我不想在 A 中添加委托并将侦听器附加到该委托。想象一下我没有类 A 的源代码的场景。
我不能在这里使用装饰模式,因为我无法修改调用 A.DoSomething() 的代码。我读过一些有关 Reflection.Emit 或 DynamicMethod 的内容,以在运行时动态更改或定义方法。可以在这里应用吗?如何应用?
I have two simple classes:
public class A
{
public void DoSomething();
}
public class Listener
{
public void OnDoSomethingCalled();
}
I want Listener.OnDoSomethingCalled() to be called automatically everytime A.DoSomething() is called. I want to do this without changing class A. I don't want to add a delegate in A and attach Listener to that delegate. Imagine the scenario where I don't have the source code for class A.
I can't use decoration pattern here because I can't modify the code that calls A.DoSomething(). I read something about Reflection.Emit or DynamicMethod to dynamically change or define a method at runtime. Can it be applied here and how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用诸如 PostSharp 之类的面向方面编程,我相信它应该可以处理这个问题(它重写了 CIL) 。
You could try Aspect Oriented Programming with something like PostSharp, which I believe should handle this (it rewrites the CIL).