<address id="ousso"></address>
<form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
  1. C語言

    運算符關鍵字as的使用

    時間:2025-03-09 12:00:29 C語言 我要投稿

    運算符關鍵字as的使用

      引導語:運算符用于執行程序代碼運算,會針對一個以上操作數項目來進行運算。以下是小編整理的運算符關鍵字as的使用,歡迎參考閱讀!

      as 運算符用于在兼容的引用類型之間執行某些類型的轉換。例如:

      C#

      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 運算符只執行引用轉換和裝箱轉換。as 運算符無法執行其他轉換,如用戶定義的轉換,這類轉換應使用強制轉換表達式來執行。

      示例

      C#

      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

      */

    【運算符關鍵字as的使用】相關文章:

    運算符關鍵字typeof的使用08-26

    c#運算符關鍵字is的使用10-30

    java語言運算符的使用10-02

    Java中運算符的使用10-17

    java的import關鍵字的使用08-17

    C語言關鍵字const的使用09-02

    C語言的關鍵字define的使用08-03

    C語言的關鍵字enum的使用09-24

    C語言關鍵字static的使用09-15

    <address id="ousso"></address>
    <form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
    1. 日日做夜狠狠爱欧美黑人