2010-11-02 10 views
0

我正在使用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

回答

1

考慮使用MethodPointcut,因爲蓋爾善意地建議我在有類似問題時使用。這給了你很大的靈活性,以決定哪些方法用於增強方面,包括檢查屬性。

+1

我還發現了另一種簡單方法:只需使用「[LogThis( AttributeExclude = true)]「來抑制特定方法的屬性。一旦你添加了這個,它甚至會更新MSVS GUI來刪除下劃線,指出哪些屬性被附加到方法中。 – Contango 2010-11-02 18:38:05