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 BaseClass
    {
        public override string ToString()
        {
            return "BaseClass";
        }
    }

    class DerivedClass : BaseClass
    {
        public override string ToString()
        {
            return "DerivedClass";
        }
    }

    class AnotherClass
    {
        public override string ToString()
        {
            return "AnotherClass";
        }
    }

    class Program
    {
        static void Main()
        {
            object[] array = new object[] { new BaseClass(), new DerivedClass(), new AnotherClass() };

            for (int i = 0; i < array.Length; i++)
            {
                BaseClass b = array[i] as BaseClass;

                if (b != null) Console.WriteLine("{0}: {1}", i, b);
                else Console.WriteLine("{0}: null", i);
            }
        }
    }

}

/* Output:

0: BaseClass
1: DerivedClass
2: null

*/

如範例所示,您需要將 as 陳述式的結果與 null 比較,以檢查轉換是否成功。As the example shows, you need to compare the result of the as expression with null to check if a conversion is successful. 從 C# 7.0 開始,您可以使用 is 陳述式來測試轉換是否成功,以及當轉換成功時有條件地指派變數。Beginning with C# 7.0, you can use the is expression both to test that a conversion succeeds and conditionally assign a variable when the conversion succeeds. 在許多情況下,這比使用 as 運算子更精簡。In many scenarios, it's more concise than using the as operator. 如需詳細資訊,請參閱 is 運算子一文的類型模式小節。For more information, see the Type pattern section of the is operator article.

備註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 的轉換以及 Boxing 轉換。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# 語言規格as 運算子For more information, see The as operator in the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also