我试图替换基类中的派生实例。它适用于动物(抽象类的简单用法),但不适用于泛型。错误在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;
    }

}

最佳答案

一个PlaceForAnimals<Dog>不是一个>(出于为其分配该类型的目的),因为它不能容纳老虎(而原始字符可以容纳)。

没有协方差,分配就根本不合法。如果要访问某些方法,则可以让基类实现一个非通用接口,并使PlaceForAnimals<Animal成为该类型。

关于c# - 更改使用泛型的抽象类的实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50823253/

10-13 07:06