2015年8月5日星期三

[C#]使用 "is" 和 "as" Operators的分別

一直都是見別人都是用as, 像是
GameObject myObject = Instantiate(refObject) as GameObject;

然後有天見到有人把 as 寫成 is 我以為他打錯了,誰料翻查下發現原來是有分別的!

長知識了~

以下就是答案:
How to: Safely Cast by Using as and is Operators (C# Programming Guide)

//In general, the as operator is more efficient because it actually returns the cast value if the cast can be made successfully. The is operator returns only a Boolean value//




我以為是他是錯手打錯了,但是其實他是放在if 裏檢查Boolean value
正如文中提及,他是這樣:
void UseIsOperator(Animal a)
    {
        if (a is Mammal)
        {
            Mammal m = (Mammal)a;
            m.Eat();
        }
    }


 所以a 是不會因為 a is Mammal 而轉成Mammal, 這句只會return true 或 false

如果用as 的話:
void UseAsOperator(object o)
    {
        Mammal m = o as Mammal;
        if (m != null)
        {
            Console.WriteLine(m.ToString());
        }
        else
        {
            Console.WriteLine("{0} is not a Mammal", o.GetType().Name);
        }
    }


那 o 就會變成Mammal了,所以Mammal m才能等於o

沒有留言:

發佈留言