HOW TO:使用 as 和 is 運算子進行安全轉型 (C# 程式設計手冊)
由於物件都是多型的,因此可以使用某個基底類別 (Base Class) 型別的變數來存放衍生型別 (Derived Type)。若要存取衍生型別的方法,您必須將值轉型回衍生型別。不過,在這種情況下嘗試進行簡單轉型卻會有擲回 InvalidCastException 的風險。這就是 C# 提供 is 和 as 運算子的原因。您可以使用這兩個運算子測試轉型能否成功,而不會擲回例外狀況 (Exception)。as 運算子通常比較有效率,因為如果轉型能夠成功,它實際會傳回轉型值。is 運算子卻只會傳回布林值,因此它可以用在只是要確定物件的型別而不必實際轉型的情況。
範例
在下列範例中,會示範如何使用 is 和 as 運算子,在無擲回例外狀況風險的情況下,從某一個參考型別 (Reference Type) 轉型成另一個型別。此外,還會示範如何使用 as 運算子搭配可為 null 的實值型別 (Nullable Type)。
class SafeCasting
{
class Animal
{
public void Eat() { Console.WriteLine("Eating."); }
public override string ToString()
{
return "I am an animal.";
}
}
class Mammal : Animal { }
class Giraffe : Mammal { }
class SuperNova { }
static void Main()
{
SafeCasting app = new SafeCasting();
// Use the is operator to verify the type.
// before performing a cast.
Giraffe g = new Giraffe();
app.UseIsOperator(g);
// Use the as operator and test for null
// before referencing the variable.
app.UseAsOperator(g);
// Use the as operator to test
// an incompatible type.
SuperNova sn = new SuperNova();
app.UseAsOperator(sn);
// Use the as operator with a value type.
// Note the implicit conversion to int? in
// the method body.
int i = 5;
app.UseAsWithNullable(i);
double d = 9.78654;
app.UseAsWithNullable(d);
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
void UseIsOperator(Animal a)
{
if (a is Mammal)
{
Mammal m = (Mammal)a;
m.Eat();
}
}
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);
}
}
void UseAsWithNullable(System.ValueType val)
{
int? j = val as int?;
if (j != null)
{
Console.WriteLine(j);
}
else
{
Console.WriteLine("Could not convert " + val.ToString());
}
}
}