Reputation: 8651
How can i call a method from a static class passing a type of dynamic in generic. Here is my static class:
public static class Log<T>
{
private readonly static ILog Logger = LogManager.GetLogger(typeof(T));
public static void LogInfo(string message)
{
Logger.Info(message);
}
}
I want to call LogInfo like this:
Log<myObject.GetType()>.LogInfo("Some String");
My question is about how to pass a type of myObject in Generic, because the type of this object is dynamic.
Upvotes: 2
Views: 1783
Reputation: 241789
I want to call LogInfo like this:
Log<myObject.GetType()>.LogInfo("Some String");
Why? Why don't you just do this:
public static class Log {
private static readonly Dictionary<Type, ILog> loggers =
new Dictionary<Type, ILog>();
public static void LogInfo(Type type, string message) {
var logger = Log.GetLoggerForType(type);
logger.Info(message);
}
public static void LogInfo<T>(string message) {
LogInfo(typeof(T), message);
}
private static ILog GetLoggerForType(Type type) {
ILog logger;
if(!loggers.TryGetValue(type, out logger)) {
logger = LogManager.GetLogger(type);
loggers.Add(type, logger);
}
return logger;
}
}
Note that this is not, Not, NOT thread safe. I wanted to communicate the idea.
Then:
Log<myObject.GetType()>.LogInfo("Some String");
can be replaced by
Log.LogInfo(myObject.GetType(), "Some String");
or you can even go one step further and add an overload that allows you to say
Log.LogInfo(myObject, "Some String");
(just call object.GetType
in LogInfo
).
Upvotes: 4