C#基礎語法:as 運算符使用實例
as 運算符類似于強制轉(zhuǎn)換操作。但是,如果無法進行轉(zhuǎn)換,則 as 返回 null 而非引發(fā)異常。
as 運算符只執(zhí)行引用轉(zhuǎn)換和裝箱轉(zhuǎn)換。as 運算符無法執(zhí)行其他轉(zhuǎn)換,如用戶定義的轉(zhuǎn)換,這類轉(zhuǎn)換應使用強制轉(zhuǎn)換表達式來執(zhí)行。
expression as type
等效于(但只計算一次 expression)
expression is type ? (type)expression : (type)null
as 運算符用于在兼容的引用類型之間執(zhí)行轉(zhuǎn)換。例如:
// 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
相關文章
C#調(diào)用C++動態(tài)庫接口函數(shù)和回調(diào)函數(shù)方法
這篇文章主要介紹了C#調(diào)用C++動態(tài)庫接口函數(shù)和回調(diào)函數(shù)方法,通過C++端編寫接口展開內(nèi)容,文章介紹詳細具有一定的參考價值,需要的小伙伴可以參考一下2022-03-03

