• C#中的as和is的使用方法


    as和is这两个关键字在C#中还是比较常见的,比如说如果你想判断一个数据的类型是否是你指定的类型,那么可以考虑使用is这个关键字,它会返回一个bool值,如果是则为true,反之则是false。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                object nNum = "123";
                if(nNum is int)
                {
                    Console.WriteLine("nNum是int类型");
                }else
                {
                    Console.WriteLine("nNum不是int类型");
                }
                Console.ReadKey();
            }
        }
    }

    as关键字在使用的时候需要注意以下几点:

    1.不能用于类型与类型之间的转换,编译的时候会出现错误;如下所示:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                int nNum = 123;
                string str = nNum as string;
                Console.ReadKey();
            }
        }
    }

    2.as关键字必须用于引用类型或者可以为null的类型值,如下所示,用于int类型转换,编译器便会报错。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                object obj = 123;
                int nNum = obj as int;
                Console.WriteLine(nNum);
                Console.ReadKey();
            }
        }
    }

    3.用as关键字进行转换时,所要转换对象的类型必须是目标类型或者是目标类型的派生类型

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyTest
    {
        public class Animal
        {
            public void Breath()
            {
                Console.WriteLine("动物呼吸");
            }    
        }
        public class Hourse : Animal { }
        class Program
        {
            static void Main(string[] args)
            {
                Hourse h = new Hourse();
                Animal a = h as Animal;
                a.Breath();
                Console.ReadKey();
            }
        }
    }
  • 相关阅读:
    0x00 Java 研习录
    0x00 Linux From Scratch 实战
    第一章:Java编程入门
    陈洋总结
    pthread_detach
    explicit用法
    Java动态加载DLL方法
    ToolHelp32 函数
    android根据子view里面的数量自动排版的一个ViewGroup
    安装CocoaPods学习
  • 原文地址:https://www.cnblogs.com/QingYiShouJiuRen/p/11351220.html
Copyright © 2020-2023  润新知