Is(is关键字判断类型的兼容性, person is Animal)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConvertTest
{
    class Program
    {
        static void Main(string[] args)
        {
            #region//as 和is
            Person p = new Person();
            if (p is Animal)
            {
                Console.WriteLine("类型兼容");
            }
            if (p is Person)
            {
                Console.WriteLine("他是person类型");
            }
            if (p is Object)
            {
                Console.WriteLine("他也是object类型的");
            }
            #endregion
            Console.Read();

        }
    }

    class Animal
    {

        public void Eat()
        {
            Console.WriteLine("吃饭");
        }
    }
    class Person : Animal
    {
        string name;
        public string Name
        {
            set { this.name = value; }
            get { return name; }
        }
        public void Work()
        {
            Console.WriteLine("gongzuo");
        }
    }
}

 

As(as只能用于引用类型的转换)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConvertTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Help h = new Help();
            ArrayList list = h.GetPerson();
            foreach (object o in list)
            {
            //把o类型转换成Person类型。
                Person ps = o as Person;
                Console.WriteLine(ps.Name);
            }
            Console.Read();

        }
    }

    class Animal
    {

        public void Eat()
        {
            Console.WriteLine("吃饭");
        }
    }
    class Person : Animal
    {
        string name;
        public string Name
        {
            set { this.name = value; }
            get { return name; }
        }
        public void Work()
        {
            Console.WriteLine("gongzuo");
        }
    }
    class Help
    {
        public ArrayList GetPerson()
        {
            ArrayList list = new ArrayList();
            for (int i = 0; i < 5; i++)
            {
                Person p = new Person();
                p.Name = i.ToString();
                list.Add(p);
            }
            return list;
        }
    }
}

 

posted on 2012-12-03 20:11  张洁MM  阅读(252)  评论(2编辑  收藏  举报