as (C# 參考)

您可以使用 as 運算子執行轉換的某些型別在相容的參考型別或 可為 Null 的型別的。 下列程式碼示範一個範例。


   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 運算子執行只參考轉換、可轉換及 Boxing 轉換。 as 運算子無法執行其他轉換方式,例如使用者定義的轉換,應該執行使用 cast 運算式。

範例

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# 語言規格。語言規格是 C# 語法和用法的限定來源。

請參閱

參考

C# 關鍵字

is (C# 參考)

?: 運算子 (C# 參考)

運算子關鍵字 (C# 參考)

概念

C# 程式設計手冊

其他資源

C# 參考