1. 程式人生 > >3.C#知識點:is和as

3.C#知識點:is和as

true color 轉換成 lec post test using line ask

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