運算子關鍵字as的使用
引導語:運算子用於執行程式程式碼運算,會針對一個以上運算元專案來進行運算。以下是小編整理的運算子關鍵字as的使用,歡迎參考閱讀!
as 運算子用於在相容的'引用型別之間執行某些型別的轉換。例如:
C#
class csrefKeywordsOperators
{
class Base
{
public override string ToString()
{
return "Base";
}
}
class Derived : Base
{ }
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
eLine(ring());
}
}
}
}
備註
as 運算子類似於強制轉換操作。但是,如果無法進行轉換,則 as 返回 null 而非引發異常。請看下面的表示式:
expression as type
它等效於以下表達式,但只計算一次 expression。
expression is type ? (type)expression : (type)null
注意,as 運算子只執行引用轉換和裝箱轉換。as 運算子無法執行其他轉換,如使用者定義的轉換,這類轉換應使用強制轉換表示式來執行。
C#
class ClassA { }
class ClassB { }
class MainClass
{
static void Main()
{
object[] objArray = new object[6];
objArray[0] = new ClassA();
objArray[1] = new ClassB();
objArray[2] = "hello";
objArray[3] = 123;
objArray[4] = 123.4;
objArray[5] = null;
for (int i = 0; i < th; ++i)
{
string s = objArray[i] as string;
e("{0}:", i);
if (s != null)
{
eLine("'" + s + "'");
}
else
{
eLine("not a string");
}
}
}
}
/*
Output:
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string
*/