孤行Blog

as and is

class Program
    {
        static void Main(string[] args)
        {
            Father f = new Father();
            Son s = new Son();
            if (f is Son)//这里为false
            {
                s = (Son)f;   //f不一定包含s,所以不能这样转换
            }
            else
            {
                s = null;
            }

            s = f as Son; 
            if (s == null)
            {
                Console.WriteLine("as类型先检查强制类型转换的有效性,如果有效,则执行强类型转换过程。否则返回null");
            }
            Console.ReadKey();
        }
    }
    class Father { }
    class Son : Father { }

posted on 2013-03-05 16:11  孤行  阅读(61)  评论(0编辑  收藏  举报