用于在兼容的引用类型之间执行转换。例如:
string s = someObject as string;
1if (s != null)
2{
3 // someObject is a string.
4}
5
备注2{
3 // someObject is a string.
4}
5
as 运算符类似于强制转换,所不同的是,当转换失败时,运算符将产生空,而不是引发异常。更严格地说,这种形式的表达式
1expression as type
2
等效于2
1expression is type ? (type)expression : (type)null
2
示例:2
1// cs_keyword_as.cs
2// The as operator.
3using System;
4class Class1
5{
6}
7
8class Class2
9{
10}
11
12class MainClass
13{
14 static void Main()
15 {
16 object[] objArray = new object[6];
17 objArray[0] = new Class1();
18 objArray[1] = new Class2();
19 objArray[2] = "hello";
20 objArray[3] = 123;
21 objArray[4] = 123.4;
22 objArray[5] = null;
23
24 for (int i = 0; i < objArray.Length; ++i)
25 {
26 string s = objArray[i] as string;
27 Console.Write("{0}:", i);
28 if (s != null)
29 {
30 Console.WriteLine("'" + s + "'");
31 }
32 else
33 {
34 Console.WriteLine("not a string");
35 }
36 }
37 }
38}
39
输出:2// The as operator.
3using System;
4class Class1
5{
6}
7
8class Class2
9{
10}
11
12class MainClass
13{
14 static void Main()
15 {
16 object[] objArray = new object[6];
17 objArray[0] = new Class1();
18 objArray[1] = new Class2();
19 objArray[2] = "hello";
20 objArray[3] = 123;
21 objArray[4] = 123.4;
22 objArray[5] = null;
23
24 for (int i = 0; i < objArray.Length; ++i)
25 {
26 string s = objArray[i] as string;
27 Console.Write("{0}:", i);
28 if (s != null)
29 {
30 Console.WriteLine("'" + s + "'");
31 }
32 else
33 {
34 Console.WriteLine("not a string");
35 }
36 }
37 }
38}
39
10:not a string
21:not a string
32:'hello'
43:not a string
54:not a string
65:not a string
7
21:not a string
32:'hello'
43:not a string
54:not a string
65:not a string
7