以下实例介绍两者区别与联系:
代码如下:
class SafeCasting
{
class Animal
{
public void Eat() { Console.WriteLine("Eating."); }
public override string ToString()
{
return "I am an animal.";
}
}
class Mammal : Animal { }
class Giraffe : Mammal { }
class SuperNova { }
static void Main()
{
SafeCasting app = new SafeCasting();
// Use the is operator to verify the type.
// before performing a cast.
Giraffe g = new Giraffe();
app.UseIsOperator(g);
// Use the as operator and test for null
// before referencing the variable.
app.UseAsOperator(g);
// Use the as operator to test
// an incompatible type.
SuperNova sn = new SuperNova();