VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之C#中is与As运算符号的使用详解

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    class IsOrAsClass
    {
        class Animal
        {
            public void Eat()
            {
                Console.WriteLine("Eating...");
            }
            public override string ToString()
            {
               return  "I am Eating";
            }
        }
        //家禽类
        class jia:Animal
        {

        }
        //狗
        class Dog : jia
        {

        }
        //鸟
        class bird
        {

        }
        static void Main()
        {
           IsOrAsClass app=new IsOrAsClass();
           //
           Dog d=new Dog();
           app.UseIsOpreate(d);
           app.UseAsOpreate(d);
           //
           bird b = new bird();
           app.UseAsOpreate(b);

        }
        //使用Is运算符
        void UseIsOpreate(Animal a)
        {
            if (a is jia)
            {
                jia j = (jia)a;
                j.Eat();
            }
        }
        //使用AS运算符
        void UseAsOpreate(object o)
        {
            jia j = o as jia;
            if (j != null)
            {
                Console.WriteLine(j.ToString());
            }
            else
            {
                Console.WriteLine("{0} is not Animal", o.GetType().Name);
            }
        }
    }
}

相关教程