假设我有一个具体的类 - 实现“IMammal”的“长颈鹿”。在我的方案,我可以创建一个通用的仓库和工厂,像这样:现在使用泛型进行类型转换
public MammalFactory : IMammalFactory
{
public IMammalRepository<T> GetMammalRepo<T>() where T: IMammal, new()
{
return new MammalRepository<T>();
}
}
MammalRepository的类型可以是长颈鹿或羚羊,只要它们都实现IMammal。到现在为止还挺好。
但是,我不能使用像这样的表达式(将无法编译,不能投):
Func<IMammalRepository<IMammal>> =() => this.factory.GetMammalRepo<Giraffe>();
我有我的类之间非常相似的方法,我想他们因子向下喜欢的东西:
//called from different implementations
public void FeedAnimalInternal(Func<IMammalRepository<IMammal>> repo, Action<IMammal> doIt)
{
var animalRepo = repo();
var animals = animalRepo.GetAnimals(); //might be giraffe or might be something else
foreach (var animal in animals) { doIt(animal); }
}
首先,为什么会不Func键<>(第一个)编译?这是一个协变事物吗?接下来,我有什么想法可以完成类似于我想要做的事情?
是的。我需要阅读更多关于它出现的协变和逆变。谢谢。 – dunnry