请考虑这一点。我想创建一个创建动物的工厂(模式,而不是创造一个新的起源)。我以为我会聪明,创建具有3件事情,我需要这个工作类,使用仿制药一劳永逸的工厂模式
- 返回一个抽象的动物委托
- 返回一个特定的动物,每动物制作方法
- 使用委托
厌倦这样了,并获得每次我需要使用工厂模式时各创建方法的一个实例,我想我会比较聪明,一次解决它所有。所以,我创造了这个漂亮的类
class Factorable<T> where T: class, new()
{
delegate T CreateDelegate();
static CreateDelegate DoCreate = new CreateDelegate (CreateSelf);
static T CreateSelf()
{
return new T();
}
}
class Factory<T> where T : Factorable<T>
{
public Factorable<T>.CreateDelegate CreationMethod ;
}
我想,很酷,我可以做出一流的(动物)从该类继承,所以我没有写和所有实例的所有具体的创建方法动物。所有这一切都要归功于泛型。几乎...看到这个:
class Animal:Factorable<Animal> {...}
class Bird:Animal {...}
Factory genesis = new Factory<Animal>();
genesis.CreationMethod = Animal.DoCreate;
Animal instance = genesis.CreateAnimal(); //instance is a brand new abstract Animal
genesis.CreationMethod = Bird.DoCreate; //lets make it create birds!
instance = genesis.CreateAnimal(); // wrong, instance is still an abstract Animal
有没有什么办法可以解决这个问题?我希望Bird继承的CreateSelf方法来创建鸟类,而不是抽象动物(不必为Bird写一个新的方法)。有没有一种方法可以指定Animal从Factorable继承,但是有它的后代用它自己的类型覆盖泛型T?
东西(这是愚蠢的代码,不工作)这样
class Animal:Factorable<Animal... or better the actual type of the class that has inherited>
也许我失去了一些东西,但一个'Animal'如何从自身'可分解'通用继承? –
mclark1129
@MikeC这在C#中是可行的。 – MarcinJuraszek