如何使用单例将派生类型传递给抽象 class
How to pass derived type to abstract class with singleton
这是我用来将单例模式应用于所有派生的代码 class。
public abstract class Service<T> where T : Service<T>, new()
{
private static T _instance = null;
public static T I()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class DerivedService : Service<DerivedService>
{
public DerivedService() { ... }
}
public class CustomService : DerivedService { ... }
所以,当我使用代码 CustomService.I();
时,类型是 DerivedService
而不是 CustomService
编辑:我通过将它转换为 CustomService
来修复它 (CustomService)CustomService.I()
。 不起作用。 (对不起)
有没有更好的方法不用转换就可以做到这一点?有什么想法,有什么建议吗?
问题源于 Derived class 这样继承的事实:
DerivedService : Service<DerivedService> 如果你想让 class 成功,你可以这样写:
public class DerivedService<T> : Service<T> where T : DerivedService<T>, new
{
{ ... }
}
这是我用来将单例模式应用于所有派生的代码 class。
public abstract class Service<T> where T : Service<T>, new()
{
private static T _instance = null;
public static T I()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class DerivedService : Service<DerivedService>
{
public DerivedService() { ... }
}
public class CustomService : DerivedService { ... }
所以,当我使用代码 CustomService.I();
时,类型是 DerivedService
而不是 CustomService
编辑:我通过将它转换为 不起作用。 (对不起)CustomService
来修复它 (CustomService)CustomService.I()
。
有没有更好的方法不用转换就可以做到这一点?有什么想法,有什么建议吗?
问题源于 Derived class 这样继承的事实: DerivedService : Service<DerivedService> 如果你想让 class 成功,你可以这样写:
public class DerivedService<T> : Service<T> where T : DerivedService<T>, new
{
{ ... }
}