按一下以給予評分及指教
TechNet
全部折疊/全部展開 全部折疊
本頁僅適用於
Microsoft Visual Studio 2005/.NET Framework 2.0

其他版本也適用於下列軟體:
C# 語言參考
as (C# 參考)

用來執行相容的參考型別之間的轉換。例如:

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

as 運算子類似於轉換 (Cast) 作業,不過,如果無法進行轉換 (Conversion),則 as 會傳回 null,而不是引發例外狀況 (Exception)。正式的說,一個具有下列格式的運算式:

expression as type

相當於

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

不同的是,expression 只被評估了一次。

請注意,as 運算子只會執行參考轉換和 boxing 轉換。as 運算子無法執行其他轉換,例如使用者定義轉換應該使用 cast 運算式執行轉換。

// cs_keyword_as.cs
// The as operator.
using System;
class Class1
{
}

class Class2
{
}

class MainClass
{
    static void Main()
    {
        object[] objArray = new object[6];
        objArray[0] = new Class1();
        objArray[1] = new Class2();
        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");
            }
        }
    }
}

輸出

0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string

如需詳細資料,請參閱 C# 語言規格中的下列章節:

  • 6 轉換

  • 7.9.10 as 運算子

社群內容   什麼是社群內容?
新增內容 RSS  註解
Processing
© 2009 Microsoft Corporation. 著作權所有,並保留一切權利。 使用規定 | 商標 | 隱私權聲明
Page view tracker