【发布时间】:2012-01-23 12:31:19
【问题描述】:
我有几个单例类,所以我尝试使用 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 的实例
【问题讨论】:
-
这个类应该有什么目的? IoC 容器可能更合适。
-
我会有更多的单例,因此我想提取创建实例的逻辑,这样从父级继承的静态方法总是可以从调用它的地方返回一个类型的实例(即使它来自后代)
-
这里有类似的讨论codeguru.com/forum/showthread.php?t=376943,看起来没有办法强迫后代成为单身人士,看起来我想要一些奇怪的东西.. :(
标签: c# inheritance static singleton