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();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/QingYiShouJiuRen/p/11351220.html
今日推荐