问题描述
在 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>您可以使用实现类似的功能。过去,我只使用过,但是它并不是免费的商业用途。
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解决方案,您可以使用,但它需要更多的工作。
There are other AOP solutions out there and you can certainly achieve something similar using Mono.Cecil, but it would require more work.
这篇关于在C#中实现方法装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!