c# - .NET 2.0等效于C#扩展方法

标签 c# oop design-patterns

如何通过将扩展方法替换为等效的.NET 2.0来将这段代码更改为.NET 2.0兼容?

public interface IMessagingService {
    void sendMessage(object msg);
}
public interface IServiceLocator {
    object GetService(Type serviceType);
}
public static class ServiceLocatorExtenstions {
    //.NET 3.5 or later extension method, .NET 2 or earlier doesn't like it
    public static T GetService<T>(this IServiceLocator loc) {
        return (T)loc.GetService(typeof(T));
    }
}
public class MessagingServiceX : IMessagingService {
    public void sendMessage(object msg) {
        // do something
    }
}
public class ServiceLocatorY : IServiceLocator {
    public object GetService(Type serviceType) {
        return null; // do something
    }
}
public class NotificationSystem {
    private IMessagingService svc;
    public NotificationSystem(IServiceLocator loc) {
        svc = loc.GetService<IMessagingService>();
    }
}
public class MainClass {
    public void DoWork() {
        var sly = new ServiceLocatorY();
        var ntf = new NotificationSystem(sly);
    }
}


非常感谢你。

最佳答案

只需从扩展方法中删除this关键字即可。

public static class ServiceLocatorExtensions
{    
    public static T GetService<T>(IServiceLocator loc) {
        return (T)loc.GetService(typeof(T));
    }
}


并通过传递您要“扩展”的对象实例,将其作为其他任何静态方法调用:

IServiceLocator loc = GetServiceLocator();
Foo foo = ServiceLocatorExtensions.GetService<Foo>(loc);


实际上,这就是.Net 3.5编译器在后台执行的操作。顺便说一句后缀Extensions您也可以删除。例如。使用Helper不要混淆别人。

关于c# - .NET 2.0等效于C#扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10410501/

相关文章:

java - 获取两个变量的百分比

c++ - 将用于串行通信的消息存储为 C++ 可行解决方案中的成员变量?

c++ - 单例实例声明为 GetInstance 方法的静态变量,它是线程安全的吗?

java - 为什么要使用 Memento 模式,因为它可以更容易完成?

c# - 尽可能晚地声明变量并将返回方法作为参数传递

c# - 在持续部署中管理密码

c# - 在 C# 中使用反射向对象添加属性

R:使用子目录和文档创建项目

c# - 确保方法逻辑在没有 bool 标志的情况下执行一次的更好方法

c# - 开放泛型类型的 ObservableCollection