欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中is与As运算符号的使用详解

程序员文章站 2023-12-19 19:51:16
如下所示:复制代码 代码如下:using system;using system.collections.generic;using system.text;namespa...
如下所示:
复制代码 代码如下:

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);
            }
        }
    }
}

上一篇:

下一篇: