[英].NET 2.0 equivalent of C# extension method
如何通过将扩展方法替换为等效的.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编译器在后台执行的操作。 Btw后缀您也可以删除Extensions
。 例如,使用Helper
不会使人们感到困惑。
svc = loc.GetService<IMessagingService>();
等于
svc = ServiceLocatorExtenstions.GetService<IMessagingService>(loc);
但是,您不必删除扩展方法,也仍然可以定位.NET 2.0-检查此信息(在Google上有更多信息): http : //kohari.org/2008/04/04/extension-methods-in-net-20 /
如果您不想使用扩展方法并避免代码中的歧义,最直接的解决方案是将所有ServiceLocatorExtenstions
方法移至IServiceLocator
接口定义内,并删除ServiceLocatorExtenstions
类。
但这可能会比这里提供的其他解决方案涉及更多的工作,顺便会产生更一致的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.