as(C# 参考)as (C# Reference)

可以使用 as 运算符在符合的引用类型或可以为 null 的类型之间执行某些类型的转换。You can use the as operator to perform certain types of conversions between compatible reference types or nullable types. 以下代码显示一个示例。The following code shows an example.


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());
            }

        }
    }
}

备注Remarks

as 运算符类似于转换运算。The as operator is like a cast operation. 但是,如果无法进行转换,则 as 会返回 null,而不是引发异常。However, if the conversion isn't possible, as returns null instead of raising an exception. 请看下面的示例:Consider the following example:

expression as type  

该代码等效于以下表达式,但 expression 变量仅进行一次计算。The code is equivalent to the following expression except that the expression variable is evaluated only one time.

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

请注意,as 运算符仅执行引用转换、可以为 null 的转换和装箱转换。Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. as 运算符无法执行其他转换,例如用户定义的转换,应使用转换表达式执行此转换。The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

示例Example

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# Language Specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See Also

C# 参考C# Reference
C# 编程指南C# Programming Guide
C# 关键字C# Keywords
isis
?: 运算符?: Operator
运算符关键字Operator Keywords