C#基本語法:as 運算符應用實例。本站提示廣大學習愛好者:(C#基本語法:as 運算符應用實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#基本語法:as 運算符應用實例正文
as 運算符相似於強迫轉換操作。然則,假如沒法停止轉換,則 as 前往 null 而非激發異常。
as 運算符只履行援用轉換和裝箱轉換。as 運算符沒法履行其他轉換,如用戶界說的轉換,這類轉換應應用強迫轉換表達式來履行。
expression as type
等效於(但只盤算一次 expression)
expression is type ? (type)expression : (type)null
as 運算符用於在兼容的援用類型之間履行轉換。例如:
// cs_keyword_as.cs
// The as operator.
using System;
class Class1
{
}
class Class2
{
}
class MainClass
{
static void Main()
{
object[] objArray = new object[6];
objArray[0] = new Class1();
objArray[1] = new Class2();
objArray[2] = "hello";
objArray[3] = 123;
objArray[4] = 123.4;
objArray[5] = null;
for (int i = 0; i < objArray.Length; ++i)
{
string s = objArray[i] as string;
Console.Write("{0}:", i);
if (s != null)
{
Console.WriteLine("'" + s + "'");
}
else
{
Console.WriteLine("not a string");
}
}
}
}
//=============================================================//
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string