【C#笔记】as 运算符

as 运算符

as 运算符用于在兼容的引用类型之间执行转换。
例如:

string s = someObject as string;
if (s != null)
{
    
// someObject is a string.
}

备注
as 运算符类似于强制转换操作。但是,如果无法进行转换,则 as 返回 null 而非引发异常。请看下面的表达式:

expression as type

它等效于以下表达式,但只计算一次 expression。

expression is type ? (type)expression : (type)null

注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用强制转换表达式来执行。

示例

代码
 1 // cs_keyword_as.cs
 2 // The as operator.
 3 using System;
 4 class Class1
 5 {
 6 }
 7 
 8 class Class2
 9 {
10 }
11 
12 class MainClass
13 {
14     static void Main()
15     {
16         object[] bjArray = 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 }
1 0:not a string
2 1:not a string
3 2:'hello'
4 3:not a string
5 4:not a string
6 5:not a string

这又是一种转换。

2010-01-03 20:14:25

原文地址:https://www.cnblogs.com/stublue/p/1661191.html