简体   繁体   English

有没有像c#的python装饰器?

[英]Is there something like python decorators for c#?

I am wrapping calls to an API and most of my methods have in their first lines: 我正在包装对API的调用,我的大部分方法都在第一行:

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

In python I would decorate those methods with something like @login_required . 在python中,我会用@login_required东西来装饰这些方法。

What would you use to refactor that type of logic in c# ? 你会用什么来重构c#中的那种逻辑?

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. C#似乎通过几个库支持它,并且由于一些CLR功能,人们也可以推出自己的库。 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). 请参阅使用.NET的面向方面编程 ,它涵盖了它的基本原理(我正在链接文章的部分内容,讨论C#的细节,但如果您正在寻找像PostSharp这样的现成解决方案,那么其余部分同样有趣,如另一个所述。回答)。

You can use any AOP tool for C# such as this one. 您可以将任何AOP工具用于C#,例如工具。

With PostSharp, software developers can encapsulate implementation patterns into classes called aspects, and apply these aspects to their code using custom attributes. 使用PostSharp,软件开发人员可以将实现模式封装到称为方面的类中,并使用自定义属性将这些方面应用于其代码。

I'm not familiar with python but it seems you are looking for "attributes" ( MSDN ), (which are pretty similar to Java annotations). 我不熟悉python,但似乎你在寻找“属性”( MSDN ),(它与Java注释非常相似)。

In particular, .NET provides the " AuthorizeAttribute ", which does exactly what you want (and maybe a little more). 特别是,.NET提供了“ AuthorizeAttribute ”,它可以完全满足您的需求(也可能更多)。 While you are not under .NET, this may still shed some light in the implementatino you are trying to achieve. 虽然你不在.NET之下,但这仍然可以为你想要实现的实现提供一些启示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM