我正在尝试替换基类中的派生实例。它适用于动物(抽象类的简单用法),但不适用于泛型。错误在SomeMethod. 有没有干净的解决方案?编辑:在另一个界面的帮助下,它确实是可行的。用 [S] 注释的代码是我原来问题的解决方案。public abstract class Animal{ public void Feed() { }}public class Tiger:Animal{}public class Dog : Animal{}public class Consumer{ public Tiger Tiger { get; set; } public Dog Dog { get; set; } public Animal FavoriteAnimal { get; set; } void SomeMethod() { // This is fine FavoriteAnimal = Tiger; FavoriteAnimal = Dog; FavoriteAnimal.Feed(); //Also fine int numberOfDogs = PlaceForDogs.CountAnimals(); int numberOfTigers = PlaceForTigers.CountAnimals(); //[S] This is doable now FavoritePlaceForAnimals = PlaceForDogs;//[S] no more ERROR int numberOfAnimalsOnMyFavoritPlace = FavoritePlaceForAnimals.CountAnimals(); // No error, but I do not get here... } public PlaceForDogs PlaceForDogs { get; set; } = new PlaceForDogs(); public PlaceForTigers PlaceForTigers { get; set; } = new PlaceForTigers(); //public PlaceForAnimals<Animal> FavoritePlaceForAnimals { get; set; } //[S] favorite place is of type IPlaceForAnimals instead of PlaceForAnimals public IPlaceForAnimals FavoritePlaceForAnimals { get; set; }}//[S]new interfacepublic interface IPlaceForAnimals{ int CountAnimals();}//[S]abstract class implements the interfacepublic abstract class PlaceForAnimals<T>:IPlaceForAnimals where T : Animal{ public List<T> Animals { get; set; } public int CountAnimals() { //special counting using properties from Animal class return 0; }}
2 回答
哔哔one
TA贡献1854条经验 获得超8个赞
APlaceForAnimals<Dog>
不是PlaceForAnimals<Animal
> (为了给它分配那种类型),因为它不能容纳老虎(而原始可以)。
如果没有协方差,分配就根本不合法。如果您想访问某些方法,您可以让基类实现一个非通用接口并使其FavoritePlaceForAnimals
成为该类型。
- 2 回答
- 0 关注
- 185 浏览
添加回答
举报
0/150
提交
取消