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

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

從鑄造類中獲取原始類

從鑄造類中獲取原始類

C#
蠱毒傳說(shuō) 2022-12-24 14:53:06
例如,我有三個(gè)類:Animal,Dog和Cat; whereAnimal是一個(gè)抽象類并將其屬性繼承給Dog和Cat。在我的程序中,我有一個(gè)用戶可以輸入的任意列表(我在 C# Form 上這樣做)。因此,我將所有輸入(無(wú)論它們是類Cat還是Dog)存儲(chǔ)到我的List<Animal>.現(xiàn)在我想從中檢索所述實(shí)例化類List<Animal>并檢索其原始類,無(wú)論是 aCat還是 a Dog。有沒(méi)有辦法做到這一點(diǎn)?
查看完整描述

3 回答

?
眼眸繁星

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊

在最新的 C# 中你可以這樣做:


Animal animal;

if (animal is Cat cat)

{

   cat.Meow();

}


查看完整回答
反對(duì) 回復(fù) 2022-12-24
?
米脂

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊

using System.Collections.Generic;

using System.Linq;


namespace ConsoleApp

{

    class Program

    {

        static void Main(string[] args)

        {

            List<Animal> animals = new List<Animal> { new Cat(), new Cat(), new Dog(), new Cat(), new Dog() };


            var dogs = animals.OfType<Dog>().ToList();

            dogs.ForEach(dog => dog.Bark());


            var cats = animals.OfType<Cat>().ToList();

            cats.ForEach(cat => cat.Meow());


            var actualTypes = animals.Select(animal => animal.GetType()).ToList();

        }


        abstract class Animal { }


        class Dog : Animal { public void Bark() { } }


        class Cat : Animal { public void Meow() { } }

    }

}


查看完整回答
反對(duì) 回復(fù) 2022-12-24
?
慕沐林林

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊

您可以使用GetType獲取類的類型。

List<Animal> lstA = new List<Animal>();

        lstA.Add(new Cat());

        lstA.Add(new Dog());

        foreach(Animal a in lstA)

        {

            Console.WriteLine("Type of {0}", a.GetType());

        }


abstract class Animal

{}

class Cat : Animal

{}

class Dog : Animal

{}


查看完整回答
反對(duì) 回復(fù) 2022-12-24
  • 3 回答
  • 0 關(guān)注
  • 95 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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