在编译时抑制单个方法的属性?

问题描述:

我正在使用PostSharp,并且想要为类中的一个方法禁用(或更改)现有的全局属性。在编译时抑制单个方法的属性?

在下面的示例中,我希望记录类“thisIsLogged()”,并且类“thisIsNotLogged()”不记录。

但是,它不起作用:属性“[LogThis(false)]”只需添加到现有的类级属性,并且无论如何发生日志记录。有任何想法吗?

[LogThis(true)] // uses PostSharp + SmartInspect to switch on logging for the entire class 
class doSomething 
{ 
    void thisIsLogged(int x) 
    { 
    // entry/exit from this class is automatically logged 
    } 
    [LogThis(false)] // aim: suppress logging for this method, if [LogThis(true)] is switched on for the entire class (however, this doesn't work as attributes are additive) 
    void thisIsNotLogged(int x) 
    { 
    // I want to suppress the entry/exit logging for this class, to reduce log size 
    // However, this *doesnt work*; logging occurs anyway 
    // as attributes are additive - any ideas? 
    } 
} 

编辑:

二手[LogThis(AttributeExclude =真)],此工作得很好(见下文溶液)。

+0

你不能简单地删除属性? – Oded 2010-11-02 17:21:02

+0

不可以 - 如果您从类中删除属性,则必须手动将其分别添加到所有100个子方法,以及所有从基类继承的类。如果将该属性应用于该类,则默认情况下该类将应用于该类中的所有方法,这更容易。幸运的是,您可以根据需要抑制单个方法或两个方法的属性(请参见下文)。 – Contango 2010-11-02 20:41:35

+0

在相关说明中,请随时尝试使用现成的SmartInspect PostSharp方面:http://code.gurock.com/p/smartinspect-postsharp/ – 2011-01-07 03:11:22

考虑使用MethodPointcut,因为盖尔善意地建议我在有类似问题时使用。这给了你很大的灵活性,以决定哪些方法用于增强方面,包括检查属性。

+1

我还发现了另一种简单方法:只需使用“[LogThis( AttributeExclude = true)]“来抑制特定方法的属性。一旦你添加了这个,它甚至会更新MSVS GUI来删除下划线,指出哪些属性被附加到方法中。 – Contango 2010-11-02 18:38:05