我试图替换基类中的派生实例.它适用于动物(简单使用抽象类),但不适用于泛型.错误在于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 interface
public interface IPlaceForAnimals
{
int CountAnimals();
}
//[S]abstract class implements the interface
public 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;
}
}
Run Code Online (Sandbox Code Playgroud)
A PlaceForAnimals<Dog>不是PlaceForAnimals<Animal>(为了分配它的类型),因为它不能容纳老虎(原来可以).
没有协方差,这项任务根本就不合法.如果要访问某些方法,可以让基类实现非泛型接口,并使其FavoritePlaceForAnimals成为该类型.