Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function decorators in c#

Tags:

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.

like image 475
jtjin Avatar asked Sep 07 '09 22:09

jtjin


People also ask

What are function decorators?

By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

What are decorators in C?

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.

When would you use a function decorator?

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.

What is decorator explain with example?

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.


2 Answers

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

like image 64
Richard Nienaber Avatar answered Sep 19 '22 04:09

Richard Nienaber


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

like image 44
Yuriy Faktorovich Avatar answered Sep 21 '22 04:09

Yuriy Faktorovich