gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:49 24 4
gpt4 key购买 nike

如何通过将扩展方法替换为等效的.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com