繁体   English   中英

避免“通过派生类型访问类型的静态成员”

[英]Avoiding “Access to a static member of a type via a derived type”

我相信这纯粹是“ Resharper”警告,但是其背后的原因( 在此进行解释)很有意义。 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);
}

一个ErrorLog为应用程序提供服务,并且其设置永不更改(还有TraceLog和ThreadLog)。 我不想复制日志记录代码,因为对于每个派生类而言,它都是完全相同的……将其保存在BaseLog中可以完美地工作。 那么如何设计我不违反该设计原则的产品呢?

这些类是静态的,因为我不想每次想记录某些东西时都实例化一个新的ErrorLog对象,并且我不想在我编写的每个类中以成员级变量的形式来浮动它们中的50个。 如果有所不同,则日志记录使用的是Microsoft的企业库。

TIA!
詹姆士

似乎您想让门保持打开状态以便扩展,而不是为了进行修改而又称为“打开关闭”原理。 这是一个值得的目标。

我的建议是丢失静态的粘连 -将函数持有者类转换为对象。 这使您可以根据需要覆盖(而不会使其他读者感到困惑)-多态仅适用于实例。

下一个需要考虑的问题是需要一个全局对象,而不是传递一个记录器实例。 创建另一个类型,该类型提供对记录器对象的单个实例访问 (旧的单身人士)

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

PS:免费赠品-也更容易测试这些对象。

暂无
暂无

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

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