你的代码完全没问题;我不会改变它。
但是,如果您想对它更加“面向对象”,那么考虑一下如何做到这一点是很有启发性的。让我们考虑您的两个案例;其他的你可以很容易地看到它们是如何实现的:
public abstract class LogType
{
public static readonly LogType Debug = new LogTypeDebug();
public static readonly LogType Error = new LogTypeError();
private LogType() {} // Prevent anyone else from making one.
public abstract void LogMessage(ILog logger, string message);
private sealed class LogTypeDebug: LogType
{
public override void LogMessage(ILog logger, string message)
{
logger.Debug(message);
}
}
private sealed class LogTypeError: LogType
{
public override void LogMessage(ILog logger, string message)
{
logger.Error(message);
}
}
}
...
//Obtain the log object the way you prefer.
private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void LogError(LogType logtype, string message)
{
logtype.LogMessage(log, message);
}
呼叫站点根本没有改变!它仍然看起来像:
LogError(LogType.Debug, "my message");
你去了:根本没有if或switch声明!“切换类型”代码已移至虚函数表中,这是它在面向对象代码中所属的位置。
A nice side effect of this technique is you never need to worry about someone casting an integer to an unsupported value of your enumerated type. The only possible values for a variable of type LogType are null or a reference to one of the singletons.