如何通过将扩展方法替换为等效的 .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);
}
}
非常感谢你。