function decorators in c#

Viewed 5938

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.

3 Answers
Related