2010-12-10 69 views
2

我相信這純粹是一個Resharper警告,但其背後的理由(解釋爲here)很合理。什麼Greg Beech的意思是,你可以調用從同級類的基類的靜態方法......在他的榜樣,他用:避免「通過派生類型訪問類型的靜態成員」

var request = (FtpWebRequest)HttpWebRequest.Create(...) 

...這是一種誤導。

那麼有沒有一種設計可以讓我在下面的課程中避免這種警告?

public abstract class BaseLog { 

    // I omitted several other properties for clarity 
    protected static string category; 
    protected static TraceEventType severity; 

    static BaseLog() { 
     category = "General"; 
     severity = TraceEventType.Information; 
    } 

    public static void Write(string message) { 
     Write(message, category, severity); 
    } 

    // Writes to a log file... it's the same code for 
    // every derived class. Only the category and severity will change 
    protected static void Write(string message, string messageCategory, TraceEventType messageSeverity) { 

     LogEntry logEntry = new LogEntry(message, messageCategory, messageSeverity); 

     // This is Microsoft's static class for logging... I'm wrapping it to 
     // simplify how it's called, but the basic principle is the same: 
     // A static class to log messages 
     Logger.Write(logEntry); 

    } 

} 


public class ErrorLog : BaseLog { 

    static ErrorLog() { 
     category = "Errors"; 
     severity = TraceEventType.Error; 
    } 

    // I can add more functionality to the derived classes, but 
    // the basic logging functionality in the base doesn't change 
    public static void Write(Exception exc) { 
     Write(exc.Message); 
    } 

} 


// Code that could call this... 
catch (Exception exc) { 
    // This line gives me the warning 
    ErrorLog.Write("You did something bad"); 
    ErrorLog.Write(exc); 
} 

One ErrorLog服務於應用程序,其設置永不改變(還有一個TraceLog和一個ThreadLog)。我不想複製日誌代碼,因爲它對每個派生類都是完全相同的......保持它在BaseLog中的工作完美。那麼我如何設計這個我不違反這個設計原則呢?

這些類是靜態的,因爲我不想在每次我想記錄某些東西時實例化一個新的對象ErrorLog,而且我不希望每個對象中有50個以每個成員級變量的形式浮動我寫的課。日誌記錄使用微軟的企業庫,如果這有所作爲。

TIA!
James

回答

5

看起來好像你想保持開放的擴展門,但不是修改又名開放閉合原則。它是一個有價值的目標。

我的建議是失去靜態粘附 - 將函數保持器類轉爲對象。這允許您根據需要覆蓋(而不是混淆其他讀者) - 多態只能用於實例。

下一個問題是需要有一個全局對象vs傳遞一個記錄器實例。 創建另一種類型,用於訪問記錄器對象的單個實例。 (舊的單身人士)

e.g. ErrorLogProvider.Instance.Write(something) 

PS:免費贈品 - 更容易測試這些對象。

+0

有趣的方法...今晚將圍繞我的頭。因此,如果我正確地跟蹤了你,`ErrorLogProvider`將是一個靜態類,其類型爲`ErrorLog`,它將在提供者的靜態構造函數中實例化並通過`Instance`屬性暴露 – 2010-12-10 05:51:58

相關問題