C#:在其他方法中包装方法
有没有办法在 C# 中透明地包装其他方法中的方法?我想实现 Moose 周围功能所做的事情: http://search.cpan .org/perldoc?Moose::Manual::MethodModifiers
编辑:我所说的透明是指不修改原始方法。
Is there a way to wrap methods in other methods transparently in C#? I want to achieve what is done by Moose's around functionality: http://search.cpan.org/perldoc?Moose::Manual::MethodModifiers
EDIT: And by transparent I mean without modifying the original method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为您正在寻找所谓的面向方面编程。有许多 C# 库可以帮助解决此问题。一种称为 PostSharp (PostSharp 的免费版本支持此功能)。这是一个与驼鹿示例类似的示例。这将创建一个 Trace 属性,您可以在其他方法上使用该属性来附加此额外功能:
您可以通过将 Trace 属性放在其前面来将其添加到方法“Foo”中:
现在,当 Foo 执行时,上面的 OnEntry 方法将在它之前运行,OnExit 将在之后立即运行。
I think you're looking for what's termed Aspect Oriented Programming. There are many C# libraries to help with this. One is called PostSharp (The free version of PostSharp supports this functionality). Here is an example similar to the moose example. This creates a Trace Attribute which you can use on other methods to tack on this extra functionality:
You would add it to method "Foo" by placing the Trace attribute right before it:
Now when Foo executes, the above OnEntry method will run before it, and OnExit will run right after.
事实上,它们在 .NET 中被称为“委托”。请参阅:
寻求帮助。
Indeed, they're called "delegates" in .NET. See:
for help.
您可以通过使用动态代理来达到相同的效果。一个示例是 Castle 动态代理。
此类框架利用 C# 反射工具来构造“代理”或“包装”类。所以,请记住这一点。因此存在一定的开销。或者,您可以使用可以通过代码生成静态创建类的框架。
You can achieve the same effect by utilizing a dynamic proxy. An example is the Castle Dynamic Proxy.
Such frameworks leverage the C# reflection facilities to construct 'proxy' or 'wrapper' classes. So, keep that in mind. There is a certain amount of overhead because of this. Alternatively you can use frameworks that can create classes statically via code generation.
不,穆斯不是这样做的。您可能想研究一些 AOP 库。
No, not the way it's done in Moose. You might want to look into some AOP library.
一些隔离库实现的功能允许用“弯路”或模拟方法替换对方法的调用。您也许可以使用相同的功能来实现您所指的拦截。有关更多详细信息,请检查以下内容:
Rhino Mocks 存根和模拟仅适用于界面?
http://research.microsoft. com/en-us/projects/moles/
http://www.typemock .com/typemock-isolator-product3/
Some isolation libraries implement functionality that allows replacing calls to methods with "detours" or mock methods. You may be able to use the same functionality to implement the interception you are referring to. For more details, check the following:
Rhino Mocks stubs and mocks are only good for interfaces?
http://research.microsoft.com/en-us/projects/moles/
http://www.typemock.com/typemock-isolator-product3/