在扩展类本身内部使用扩展方法

2024-01-01

假设我有一个界面,如下所示:

public interface ILoggable
{
    void Log(Func<string> message, Logger.Type type);
}

还有一些扩展方法,如下所示:

public static class Logger
{
    public static void Log(this ILoggable loggable, Func<string> message) { loggable.Log(message, Type.Information); }
    public static void Log(this ILoggable loggable, string prefix, byte[] data, int len) { /* snip */ }
    public static void Log(this ILoggable loggable, Exception ex) { /* snip */ }
    // And so on...
}

那么在任何class CoreService : ServiceBase, ILoggable或者这样我实现了public void Log(Func<string> message, Logger.Type type)到我喜欢的任何东西(公共修饰符有点无聊......)并使用所有扩展方法来进行实际的日志记录。

到目前为止还好……还是不太好?这种做法有什么问题吗?如果没有,那么为什么会带来不便:

catch (Exception ex) {
    this.Log(ex); // this works
    Log(ex); // this goes not

It seems like a reasonable approach to me in itself1 - but the requirement to explicitly state this is just part of how the language works around extension methods. I suspect this makes aspects of the language specification cleaner, and this requirement is sufficiently rare (and the workaround sufficiently easy) that it was felt to be better to go with the current solution than to make things more complicated just to avoid five characters in a relatively rare scenario.

简单名称的成员查找(C# 4 规范的第 7.6.2 节)已经足够复杂,但不会让它变得更糟。不要忘记简单名称可以引用类型或类型参数以及方法。那里已经发生了很多事情。

当我开始工作时,我将检查第 7.6.5.2 节(扩展方法调用)周围是否有任何注释,其中提供了有关此内容的“内部信息”。


1 On reflection, it does seem slightly odd for the entity doing the logging to also want to log other things - the only kind of exception I'd expect it to see would be when the logging is failing, in which case logging the exception would fail too.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在扩展类本身内部使用扩展方法 的相关文章

随机推荐