.NET 2.0相当于C#扩展方法

Tom*_*Tom 1 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢你.

Ser*_*kiy 6

只需this从扩展方法中删除关键字.

public static class ServiceLocatorExtensions
{    
    public static T GetService<T>(IServiceLocator loc) {
        return (T)loc.GetService(typeof(T));
    }
}
Run Code Online (Sandbox Code Playgroud)

并通过传递您正在"扩展"的对象实例将其称为任何其他静态方法:

IServiceLocator loc = GetServiceLocator();
Foo foo = ServiceLocatorExtensions.GetService<Foo>(loc);
Run Code Online (Sandbox Code Playgroud)

实际上这就是.Net 3.5编译器在幕后做的事情.Btw后缀Extensions你也可以删除.例如,用Helper不要混淆人.