[英]Generic type methods shortcut
I recently wrote a logger class which gets initialized in my IoC
. 我最近写了一个记录器类,该类在
IoC
初始化。
public static class IoC() {
public static ILogger Logger => IoC.Get<ILogger>();
[...]
}
ILogger
has generic type method: ILogger
具有通用类型方法:
void Log<T>(string message, LogLevel level = LogLevel.Info);
So that I could maintain my logs better. 这样我可以更好地维护日志。
I'm able to call it like: 我可以这样称呼它:
IoC.Logger.Log<GeneralLog>("My message");
Now, that is pretty long line. 现在,这是很长的线。
Is there a possibility in C#, so that I could declare a shortcut for the Log<T>()
method with pre-defined generic type? C#中是否有可能,这样我可以为具有预定义泛型类型的
Log<T>()
方法声明快捷方式?
For example: 例如:
Instead of 代替
IoC.Logger.Log<GeneralLog>("My message");
I could write 我可以写
IoC.Logger.General("Message"); // and this should reference to IoC.Logger.Log<GeneralLog>
IoC.Logger
is of type ILogger
, which presumably is outside your control, so you can't edit it to add that method. IoC.Logger
的类型为ILogger
,这可能超出了您的控制范围,因此您无法对其进行编辑以添加该方法。
You could write it as an extension method though: 您可以将其编写为扩展方法:
public static class ILoggerExtensions
{
public static void General(this ILogger logger, string message)
{
logger.Log<GeneralLog>(message);
}
}
Now you can call .General(string)
on each ILogger
, such as the one returned by IoC.Logger
. 现在,您可以在每个
ILogger
上调用.General(string)
,例如IoC.Logger
返回的IoC.Logger
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.