3 回答

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
在最新的 C# 中你可以這樣做:
Animal animal;
if (animal is Cat cat)
{
cat.Meow();
}

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() { } }
}
}
- 3 回答
- 0 關(guān)注
- 95 瀏覽
添加回答
舉報(bào)