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#數(shù)組中List, Dictionary的相互轉(zhuǎn)換問題
這篇文章主要介紹了C#數(shù)組中List, Dictionary的相互轉(zhuǎn)換問題,本文給大家介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2016-12-12
C/C++與Java各數(shù)據(jù)類型所占字節(jié)數(shù)的詳細比較
本篇文章主要是對C/C++與Java各數(shù)據(jù)類型所占字節(jié)數(shù)進行了詳細的對比。需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01

