【发布时间】:2014-04-01 23:07:05
【问题描述】:
考虑一下。我想创建一个创造动物的工厂(模式,而不是计划新的起源)。我以为我会很聪明,并创建一个包含我需要的 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 ;
}
我想,很酷,我可以让顶级类(Animal)继承这个类,这样我就不必为所有动物编写和实例化所有具体的创建方法。多亏了泛型,这一切都将完成。几乎……看到这个:
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 方法来创建 Birds,而不是抽象 Animals(无需为 Bird 编写新方法)。有没有办法指定 Animal 继承自 Factorable 但让其后代用自己的类型覆盖泛型 T?
像这样的东西(这是愚蠢的代码,不起作用)
class Animal:Factorable<Animal... or better the actual type of the class that has inherited>
【问题讨论】:
-
也许我遗漏了一些东西,但是
Animal如何从自身的泛型Factorable<Animal>继承? -
@MikeC 这在 C# 中是可能的。
标签: c# oop generics inheritance