Frage

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#?

War es hilfreich?

Lösung

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

Andere Tipps

You can use any AOP tool for C# such as this one.

With PostSharp, software developers can encapsulate implementation patterns into classes called aspects, and apply these aspects to their code using custom attributes.

I'm not familiar with python but it seems you are looking for "attributes" (MSDN), (which are pretty similar to Java annotations).

In particular, .NET provides the "AuthorizeAttribute", which does exactly what you want (and maybe a little more). While you are not under .NET, this may still shed some light in the implementatino you are trying to achieve.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top