我有几个单例类,所以我尝试创建一个具有方法GetInstance(params)的父类BaseClass和派生类,它应该实现这个方法并返回自己的实例(所以我不必转换它们)......由于它们是单例的,因此该方法应该是静态的,但是不允许覆盖静态方法。最好的编码方法是什么?我想要的示例代码:
public class Base {
public static virtual T GetInstance<T>() where T : class;
}
public class Derived {
Derived instance;
public static override T GetInstance<T>() where T : typeOf(this){
if (instance == null) {
instance = new Derived();
}
return instance;
}
}
在这段代码之外,我想要调用...
Derived.GetInstance().SomeDerivedMethod()
不
(Derived.GetInstance() as Derived).SomeDerivedMethod() and not
new Derived().getInstance().SomeDerivedMethod()
我知道这并不好,而且我对类型T缺乏经验,所以欢迎任何建议。 谢谢
编辑: 或者如果可以在Base中定义GetInstance()方法,这样派生类就不需要覆盖它了,但它将返回从哪里调用的类的实例... Derived.GetInstance()将返回Derived的实例。