更改使用泛型的抽象类的实例

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

    }


}



qq_笑_17
浏览 186回答 2
2回答

哔哔one

APlaceForAnimals<Dog>不是PlaceForAnimals<Animal> (为了给它分配那种类型),因为它不能容纳老虎(而原始可以)。如果没有协方差,分配就根本不合法。如果您想访问某些方法,您可以让基类实现一个非通用接口并使其FavoritePlaceForAnimals成为该类型。
打开App,查看更多内容
随时随地看视频慕课网APP