views:

675

answers:

3

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.

+4  A: 

You can do that using Post Sharp. Check out the demo video for instructions.

Yuriy Faktorovich
Post Sharp looks pretty awesome, but adding a framework to my tiny project might be a bit overkill for what I needed the function decorators for. Thanks anyway :D
jtjin
It's really simple, just adding a reference and inheriting an attribute.
Yuriy Faktorovich
+4  A: 

The way I achieve this is through AOP frameworks like Castle Dynamic Proxy, Spring.NET or even the Policy Injection Application Block.

Richard Nienaber
Thanks for the pointers to AOP - I think adding a framework to my tiny project might be a bit overkill though, at least for what I wanted the decorators in the first place. Thanks anyway :)
jtjin
+2  A: 

you can sort of achieve that by "ContextBoundObject" in the .NET framework. but it's a bit convoluted because it basically uses .net remoting infrastructure to intercept method calls. (the runtime overhead is minimum if your calls are within the same app domain but just across different "context"). so the better approaches would be the ones mentioned above by the other posters.