猿问

从铸造类中获取原始类

例如,我有三个类:Animal,DogCat; whereAnimal是一个抽象类并将其属性继承给DogCat。在我的程序中,我有一个用户可以输入的任意列表(我在 C# Form 上这样做)。因此,我将所有输入(无论它们是类Cat还是Dog)存储到我的List<Animal>.

现在我想从中检索所述实例化类List<Animal>并检索其原始类,无论是 aCat还是 a Dog。有没有办法做到这一点?


蛊毒传说
浏览 73回答 3
3回答

眼眸繁星

在最新的 C# 中你可以这样做:Animal animal;if (animal is Cat cat){&nbsp; &nbsp;cat.Meow();}

米脂

using System.Collections.Generic;using System.Linq;namespace ConsoleApp{&nbsp; &nbsp; class Program&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<Animal> animals = new List<Animal> { new Cat(), new Cat(), new Dog(), new Cat(), new Dog() };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var dogs = animals.OfType<Dog>().ToList();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dogs.ForEach(dog => dog.Bark());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var cats = animals.OfType<Cat>().ToList();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cats.ForEach(cat => cat.Meow());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var actualTypes = animals.Select(animal => animal.GetType()).ToList();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; abstract class Animal { }&nbsp; &nbsp; &nbsp; &nbsp; class Dog : Animal { public void Bark() { } }&nbsp; &nbsp; &nbsp; &nbsp; class Cat : Animal { public void Meow() { } }&nbsp; &nbsp; }}

慕沐林林

您可以使用GetType获取类的类型。List<Animal> lstA = new List<Animal>();&nbsp; &nbsp; &nbsp; &nbsp; lstA.Add(new Cat());&nbsp; &nbsp; &nbsp; &nbsp; lstA.Add(new Dog());&nbsp; &nbsp; &nbsp; &nbsp; foreach(Animal a in lstA)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Type of {0}", a.GetType());&nbsp; &nbsp; &nbsp; &nbsp; }abstract class Animal{}class Cat : Animal{}class Dog : Animal{}
随时随地看视频慕课网APP
我要回答