在C#中实现方法装饰器 [英] Implement method decorators in C#

查看:95
本文介绍了在C#中实现方法装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 中可以实现函数装饰器来扩展函数和方法的行为。

In python is possible to implement function decorators to extend the behavior of functions and methods.

特别是我将设备库从 python 迁移到 C# 。与设备的通信可能会产生错误,应该自定义异常。

In particular I'm migrating a device lib from python to C#. The communication with device can generate errors which should reraised with custom exception.

python 中,我将这样写:

@device_error_wrapper("Device A", "Error while setting output voltage.")   
def set_voltage(self, voltage):
    """
    Safely set the output voltage of device.
    """
    self.__handle.write(":source:voltage:level {0}".format(voltage))

此方法调用将扩展为

try:
    self.__handle.write(":source:voltage:level {0}".format(voltage))
except Error:
    raise DeviceError("Error while setting output voltage.", "DeviceA")

使用这种模式,您可以轻松地包装和扩展方法,而无需在每个方法中写入每个 try-except 子句。

With this pattern you can easily wrap and extend methods without having to write every try-except clause in every method.

是否可以使用 C#实现类似的模式?

Is it to possible to implement a similar pattern using C#?

如果需要执行装饰器( device_error_wrapper ),请告诉。

If the implementation of the decorator (device_error_wrapper) is needed, please tell.

推荐答案

p>您可以使用面向方面的编程实现类似的功能。过去,我只使用过 PostSharp ,但是它并不是免费的商业用途。

You can achieve something similar using Aspect Oriented Programming. I've only used PostSharp in the past but it's not free for commercial use though.

还有其他AOP解决方案,您可以使用 Mono .Cecil ,但它需要更多的工作。

There are other AOP solutions out there and you can certainly achieve something similar using Mono.Cecil, but it would require more work.

Reza Ahmadi写了一篇很好的小介绍文章,名为

Reza Ahmadi wrote a nice little introduction article called Aspect Oriented Programming Using C# and PostSharp. It can give you a clear enough idea of what to expect and how it works.

这篇关于在C#中实现方法装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆