加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 05:59:48 所属栏目:百科 来源:网络整理
导读:如下所示: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class IsOrAsClass { class Animal { public void Eat() { Console.WriteLine("Eating..."); } public override string
如下所示:
复制代码 代码如下:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读