28 9月 2011

[C#] 用 as 取代強制型態轉換

as 並不會回傳 exception,當無法轉換時會回傳 null


// Bad 
object o = 1.3; 
try
{
  string str = (string)o; 
} 
catch(InvalidCastException ex){...}

// Good
string str = o as string;
if(null != str){...}

沒有留言:

張貼留言