as 运算符用于执行可兼容类型之间的转换。as 运算符用在以下形式的表达式中:
expression as type
此处:
expression
引用类型的表达式。
type
引用类型。
备注
as 运算符类似于类型转换,所不同的是,当转换失败时,as 运算符将产生空,而不是引发异常。在形式上,这种形式的表达式:
expression as type
等效于:
expression is type ? (type)expression : (type)null
只是 expression 只被计算一次。
示例
// cs_keyword_as.cs
// The as operator
using System;
class MyClass1
{
}
class MyClass2
{
}
public class IsTest
{
public static void Main()
{
object [] myObjects = new object[6];
myObjects[0] = new MyClass1();
myObjects[1] = new MyClass2();
myObjects[2] = "hello";
myObjects[3] = 123;
myObjects[4] = 123.4;
myObjects[5] = null;
for (int i=0; i<myObjects.Length; ++i)
{
string s = myObjects[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#中的as运算符
最新推荐文章于 2023-10-03 15:24:44 发布