用于安全的类型转换
转换失败返回null
class Animal
{
public string Name {get;set;}
}
class Dog:Animal
{
public void Bark()
{
Console.WriteLine("wang wang!");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Dog();
Dog myDog = myAnimal as Dog;
if(my Dog != null)
{
myDog.Bark();// Output: wang wang!
}
else
{
Console.WriteLine("The animal is not a dog");
}
}
}