as (C# 參考)

as 運算子可用來執行相容參考型別之間的特定類型轉換。 例如:


   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,而不會引發例外狀況 (Exception)。 請參考下列運算式:

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# 參考