更新:2007 年 11 月
as 运算符用于在兼容的引用类型之间执行某些类型的转换。例如:
C# | 复制代码 |
---|---|
class csrefKeywordsOperators { class Base { public override string ToString() { return "Base"; } } class Derived : Base { } class Program { static void Main() { Derived d = new Derived(); Base b = d as Base; if (b != null) { Console.WriteLine(b.ToString()); } } } } |
备注
as 运算符类似于强制转换操作。但是,如果无法进行转换,则 as 返回 null 而非引发异常。请看下面的表达式:
复制代码 | |
---|---|
expression as type |
它等效于以下表达式,但只计算一次 expression。
复制代码 | |
---|---|
expression is type ? (type)expression : (type)null |
注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用强制转换表达式来执行。
示例
C# | 复制代码 |
---|---|
class ClassA { } class ClassB { } class MainClass { static void Main() { object[] objArray = new object[6]; objArray[0] = new ClassA(); objArray[1] = new ClassB(); 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"); } } } } /* Output: 0:not a string 1:not a string 2:'hello' 3:not a string 4:not a string 5:not a string */ |
C# 语言规范
有关更多信息,请参见 C# 语言规范中的以下各章节:
6 转换
7.9.11 as 运算符