泛型基类呢?
public class Poo { }
public class RadioactivePoo : Poo { }
public class BaseAnimal<PooType>
where PooType : Poo, new() {
PooType Excrement {
get { return new PooType(); }
}
}
public class Dog : BaseAnimal<Poo> { }
public class Cat : BaseAnimal<RadioactivePoo> { }
编辑:一种新的解决方案,使用扩展方法和标记接口...
public class Poo { }
public class RadioactivePoo : Poo { }
public interface IPooProvider<PooType> { }
public static class IPooProviderExtension {
public static PooType StronglyTypedExcrement<PooType>(
this IPooProvider<PooType> iPooProvider)
where PooType : Poo {
BaseAnimal animal = iPooProvider as BaseAnimal;
if (null == animal) {
throw new InvalidArgumentException("iPooProvider must be a BaseAnimal.");
}
return (PooType)animal.Excrement;
}
}
public class BaseAnimal {
public virtual Poo Excrement {
get { return new Poo(); }
}
}
public class Dog : BaseAnimal, IPooProvider<Poo> { }
public class Cat : BaseAnimal, IPooProvider<RadioactivePoo> {
public override Poo Excrement {
get { return new RadioactivePoo(); }
}
}
class Program {
static void Main(string[] args) {
Dog dog = new Dog();
Poo dogPoo = dog.Excrement;
Cat cat = new Cat();
RadioactivePoo catPoo = cat.StronglyTypedExcrement();
}
}
这样Dog和Cat都从Animal继承(如注释中所述,我的第一个解决方案没有保留继承)。
有必要使用标记接口显式标记类,这很痛苦,但是也许这可以给您一些想法...
第二编辑@Svish:我修改了代码以清楚地表明扩展方法没有以任何方式强制执行以下事实:iPooProvider
继承自BaseAnimal
。您说“甚至更强类型”是什么意思?