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//