用于在兼容的引用类型之间进行转换
as 运算符类似于强制转换操作;但是,如果转换不可行,as 会返回 null 而不是引发异常。更严格地说,这种形式的表达式
expression as type
等效于
expression is type ? (type)expression : (type)null
只是 expression 只被计算一次。
注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用 cast 表达式来执行。
使用举例:
//
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 " );
}
}
}
}
// 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