一级日韩免费大片,亚洲一区二区三区高清,性欧美乱妇高清come,久久婷婷国产麻豆91天堂,亚洲av无码a片在线观看

C語(yǔ)言

運算符關(guān)鍵字as的使用

時(shí)間:2025-03-09 12:00:29 C語(yǔ)言 我要投稿

運算符關(guān)鍵字as的使用

  引導語(yǔ):運算符用于執行程序代碼運算,會(huì )針對一個(gè)以上操作數項目來(lái)進(jìn)行運算。以下是小編整理的運算符關(guān)鍵字as的使用,歡迎參考閱讀!

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

  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 運算符類(lèi)似于強制轉換操作。但是,如果無(wú)法進(jìn)行轉換,則 as 返回 null 而非引發(fā)異常。請看下面的表達式:

  expression as type

  它等效于以下表達式,但只計算一次 expression。

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

  注意,as 運算符只執行引用轉換和裝箱轉換。as 運算符無(wú)法執行其他轉換,如用戶(hù)定義的轉換,這類(lèi)轉換應使用強制轉換表達式來(lái)執行。

  示例

  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

  */

【運算符關(guān)鍵字as的使用】相關(guān)文章:

運算符關(guān)鍵字typeof的使用08-26

c#運算符關(guān)鍵字is的使用10-30

java語(yǔ)言運算符的使用10-02

Java中運算符的使用10-17

java的import關(guān)鍵字的使用08-17

C語(yǔ)言關(guān)鍵字const的使用09-02

C語(yǔ)言的關(guān)鍵字define的使用08-03

C語(yǔ)言的關(guān)鍵字enum的使用09-24

C語(yǔ)言關(guān)鍵字static的使用09-15

一级日韩免费大片,亚洲一区二区三区高清,性欧美乱妇高清come,久久婷婷国产麻豆91天堂,亚洲av无码a片在线观看