object o = Factory.GetValue();
int i = o as int; // 編譯錯誤:值型別不可為 null
因為 as 失敗回傳 null,但值型別不可為 null。此時改用 is 模式比對(C# 7+):
if (o is int value)
{
// value 直接可用,已轉型完成
Console.WriteLine(value);
}
或傳統寫法:
if (o is int)
{
int i = (int)o; // 安全,已經過 is 檢查
}
is:型別檢查,回傳 bool,不轉型as:安全轉型,失敗回傳 null(僅限參考型別/可為 null 的值型別)// ❌ 冗餘:as 已經包含檢查
if (o is MyType)
t = o as MyType;
// ❌ 冗餘:重複 as 運算
if ((o as MyType) != null)
t = o as MyType;
// ✅ 正確:單次 as + null 檢查
MyType t = o as MyType;
if (t != null) { ... }
foreach (MyType t in collection)
t.DoStuff();
// 等同於:
IEnumerator e = collection.GetEnumerator();
while (e.MoveNext())
{
MyType t = (MyType)e.Current; // 非泛型 IEnumerable 必須強制轉型
t.DoStuff();
}
泛型 IEnumerable<T> 則無需轉型,編譯器產生型別安全程式碼。
as + null 檢查is 模式比對(C# 7+)或 is + 強制轉型(T)o,as/is 忽略使用者定義轉型