如何通過將擴展方法替換爲等效的.NET 2.0來將這段代碼更改爲與.NET 2.0兼容?.NET 2.0等效的C#擴展方法
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);
}
}
非常感謝。
爲什麼你必須使用擴展方法?將擴展類用作IServiceLocator上的函數提供者。 – SimpleVar