设为首页 加入收藏

TOP

3.C#知识点:is和as
2019-09-02 23:55:48 】 浏览:13
Tags:3.C# 知识点

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
    {

    }
}

有一点我要强调一下就是子类可以转换父类,但是父类不能转换为子类,这就比如现在这个社会。你父母的东西是你的,但是你的东西还是你的一样。

 

            Father F2 = new Father();
            Child C1 = (Child)F2;

 

第二句代码转换的时候就会失败了。因为父类不能强转换为子类。Father不能转换为Child,但是我们如果用As进行转换的话为得到一个null的c1对象。

总结 

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

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

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

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇可空值类型 下一篇多线程编程学习笔记——async和aw..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目