码迷,mamicode.com
首页 > Windows程序 > 详细

3.C#知识点:is和as

时间:2017-12-21 00:03:20      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:key   using   pos   需要   null   ast   失败   pac   区别   

IS和AS 都是用于类型转换的操作。

但是这两个有什么区别呢?

简单的来说 is 判断成立则返回True,反之返回false。as 成立则返回要转换的对象,不成立则返回Null。

下面掏一手代码来说明一下。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IsAndAsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            object child = new Child();
            bool b1 = (child is Father);
            bool b2 = (child is Mother);
            Console.WriteLine(b1);//返回true
            Console.WriteLine(b2);//返回false
            Console.ReadKey();
        }
    }
    public class Father
    {

    }
    public class Child:Father
    {

    }
    public class Mother
    {

    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IsAndAsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            object child = new Child();
            //bool b1 = (child is Father);
            //bool b2 = (child is Mother);
            //Console.WriteLine(b1);//返回true
            //Console.WriteLine(b2);//返回false
            //Console.ReadKey();
            Father f1 = child as Father;//可以得到转换成功,得到对象
            Mother m1 = child as Mother;//转换失败,m1的值为null
        }
    }
    public class Father
    {

    }
    public class Child:Father
    {

    }
    public class Mother
    {

    }
}

总结 

由他们返回值就可以简单的知道他们的用法。

is 主要用于类型推断,而不需要实际的转换。

as 主要用于正在的类型转换。

 

3.C#知识点:is和as

标签:key   using   pos   需要   null   ast   失败   pac   区别   

原文地址:http://www.cnblogs.com/DingKing/p/8076341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!