假設我有一個具體的類 - 實現「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