第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

更改使用泛型的抽象類的實(shí)例

更改使用泛型的抽象類的實(shí)例

C#
qq_笑_17 2021-08-07 18:11:24
我正在嘗試替換基類中的派生實(shí)例。它適用于動(dòng)物(抽象類的簡單用法),但不適用于泛型。錯(cuò)誤在SomeMethod. 有沒有干凈的解決方案?編輯:在另一個(gè)界面的幫助下,它確實(shí)是可行的。用 [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貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊

APlaceForAnimals<Dog>不是PlaceForAnimals<Animal> (為了給它分配那種類型),因?yàn)樗荒苋菁{老虎(而原始可以)。

如果沒有協(xié)方差,分配就根本不合法。如果您想訪問某些方法,您可以讓基類實(shí)現(xiàn)一個(gè)非通用接口并使其FavoritePlaceForAnimals成為該類型。


查看完整回答
反對 回復(fù) 2021-08-07
  • 2 回答
  • 0 關(guān)注
  • 206 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)