1 形式:
as :
object obj = Factory.GetObject();
MyType t = obj as MyType;
if (null != t)
{
// work with t, it is a MyType;
}
else
{
// report failure;
}
強制轉換:
object obj = Factory.GetObject();
try
{
MyType t;
t = (MyType)obj;
}
catch (InvalidCastException ex)
{
// report failure.
}
強制轉換不僅要捕獲異常,還要判斷obj是否爲null, 因爲null可以被強制轉成任何類型;
as 更安全;
使用時只需檢查返回的引用是否爲null既可;
2 as 不能配合值類型
int i = obj as int; // 編譯錯誤;