Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like python decorators for c#?

Tags:

c#

unity3d

gree

I am wrapping calls to an API and most of my methods have in their first lines:

if ( !Gree.Authorizer.IsAuthorized() )
{
    return;
}

In python I would decorate those methods with something like @login_required.

What would you use to refactor that type of logic in c#?

like image 711
Macarse Avatar asked Nov 07 '12 11:11

Macarse


People also ask

Are there decorators in C?

Decorator 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.

Can Python decorators be used on classes?

Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.

When should I use Python decorators?

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.

Why decorators in Python are pure genius?

Decorators are a prime-time example of a perfectly implemented feature. It does take a while to wrap your head around, but it's worth it. As you start using them, you'll notice how they don't overcomplicate things and make your code neat and snazzy.


1 Answers

You are looking for a subset of a more general programming methodology called Aspect Oriented Programming.

C# seems to support it through several libraries, and one can also roll out his own, thanks to some of the CLR features. See Aspect Oriented Programming using .NET which covers its basic principles (I am linking the part of the article talking about the specifics of C#, but the rest is equally interesting if you are looking for ready-made solutions like PostSharp, as mentioned in another answer).

like image 159
didierc Avatar answered Oct 05 '22 08:10

didierc