Is there a C# analog for Python's function decorators? It feels like it's doable with attributes and the reflection framework, but I don't see a way to replace functions at runtime.
Python decorators generally work this way:
class decorator(obj): def __init__(self, f): self.f = f def __call__(self, *args, **kwargs): print "Before" self.f() print "After" @decorator def func1(): print "Function 1" @decorator def func2(): print "Function 2"
Calling func1 and func2 would then result in
Before Function 1 After Before Function 2 After
The idea is that decorators will let me easily add common tasks at the entry and exit points of multiple functions.
By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects, called decorators. Using decorators you can wrap objects countless number of times since both target objects and decorators follow the same interface.
You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.
A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.
The way I achieve this is through AOP frameworks like Castle Dynamic Proxy, Spring.NET or even the Policy Injection Application Block.
You can do that using Post Sharp. Check out the demo video for instructions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With