亚洲国产日韩欧美在线a乱码,国产精品路线1路线2路线,亚洲视频一区,精品国产自,www狠狠,国产情侣激情在线视频免费看,亚洲成年网站在线观看

運算符關鍵字as的使用

時間:2025-12-08 23:03:03 C語言

運算符關鍵字as的使用

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

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

  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 而非引發(fā)異常。請看下面的表達式:

  expression as type

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

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

  注意,as 運算符只執(zhí)行引用轉換和裝箱轉換。as 運算符無法執(zhí)行其他轉換,如用戶定義的轉換,這類轉換應使用強制轉換表達式來執(zhí)行。

  示例

  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的使用12-27

c#運算符關鍵字is的使用02-03

java語言運算符的使用01-28

Java中運算符的使用11-14

java的import關鍵字的使用11-27

C語言的關鍵字define的使用11-30

Java transient關鍵字使用總結02-05

C語言register關鍵字的使用12-27

C語言的關鍵字enum的使用11-25