我创建了一个记录器具有以下接口传递类型为构造函数的参数或通用
public interface ILogger
{
void Log(LogLevel logLevel, string message, [CallerMemberName] string callingMemberName = "");
Exception Log(Exception ex, [CallerMemberName] string callingMemberName = "");
}
一个我想要打印的东西时Log()
被称为是该方法的名字连同其Type
应打印。方法名称易于使用[CallerMemberName]
属性获取。要获得类型I或者需要使用StackTrace
(这是缓慢和不可预知的)或通过它。
我决定我想通过它,但想出了办法做到这一点。
1)它传递到构造
public abstract class AbstractLogger : ILogger
{
protected LogLevel minLogLevel;
protected Type callingMemberType;
protected AbstractLogger(Type callingMemberType, LogLevel minLogLevel)
{
this.callingMemberType = callingMemberType;
this.minLogLevel = minLogLevel;
}
//abstract methods omitted
}
2)传递它作为一种通用
public abstract class AbstractLogger<T> : ILogger
{
protected LogLevel minLogLevel;
protected Type callingMemberType;
protected AbstractLogger(LogLevel minLogLevel)
{
this.callingMemberType = typeof(T);
this.minLogLevel = minLogLevel;
}
//abstract methods omitted
}
两者都要求每个班都有自己的实例,但我确定接着就,随即。
这是呼叫会是什么样子为他们每个人:
//pass in to constructor
public ILogger MyLogger = new ConcreteLogger(typeof(MyClass, LogLevel.DEBUG);
//pass as a generic
public ILogger MyLogger = new ConcreteLogger<MyClass>(LogLevel.DEBUG);
的问题是,没有任何理由,更喜欢一个方法比其他?
就我个人而言,因为您实际上并不是在编写泛型代码,所以我会在'Type'中传入,但是您可能会发现另一个看起来更好。但我个人建议只使用现有的库,而不是滚动自己的日志代码。 – juharr
我知道“泛型”是在编译时解决的,而“typeof”方法可能是在运行时。 –