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