4

C# – 學習筆記II(ver 1) – NaCl's Blog

 2 years ago
source link: https://fredxxx123.wordpress.com/2008/05/29/c-%e5%ad%b8%e7%bf%92%e7%ad%86%e8%a8%98ii%ef%bc%88ver-1%ef%bc%89/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C# – 學習筆記II(ver 1)

嗯~比較小、比較隨性的筆記都會歸類在這吧~
加上重要關鍵字應該會比較方便找…吧?
我對沒有 Tag 功能的無名感到絕望

關鍵字: as 、 is


as 是轉型運算子,不過他在轉型失敗之後並不會出現錯誤,而是回傳一個 null 。

 expression as type

expression
     參考型別運算式。
type
     參考型別。

其實就等同於

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

※「is」是另一個關鍵字,下面會解釋

一個簡單的範例:

 using System;
 class MyClass1 { }
 class MyClass2 { }

 public class IsTest
 {
     public static void Main()
     {
         object[] myObjs = new object[6];
         myObjs[0] = new MyClass1();
         myObjs[1] = new MyClass2();
         myObjs[2] = "hello";
         myObjs[3] = 123;
         myObjs[4] = 123.4;
         myObjs[5] = null;

         for (int i = 0; i < myObjs.Length; i++)
         {
             string s = myObjs[i] as string;
             Console.Write("{0}:", i);
             if (s != null)
                 Console.WriteLine("字串 – {0}", s);
             else
                 Console.WriteLine("這不是字串!");
         }
      &nbsp
;  // 停下來看結果
         Console.ReadLine();
     }
 }

as 範例檔


is 運算子是用來檢查物件在執行時期(run-time)的型別是否相容於某種形別。

 expression is type

expression
     參考型別運算式。
type
     參考型別。

也就是說,當 (type)(expression) 不會拋出例外,結果就為 true。
如果在編譯時期就知道該運算一定是 true 或 false ,則會發出警告。

is 不能多載。

 class MyClass1 {}
 class MyClass2 {}

 class IsTest
 {
     public static void Test(object o)
     {
         MyClass1 a;
         MyClass2 b;

         if (o is MyClass1)
         {
             Console.WriteLine("o 是 MyClass1");
             a = (MyClass1)o;
             // 其他使用 a 的部分
         }
         else if (o is MyClass1)
         {
             Console.WriteLine("o 是 MyClass2");

b = (MyClass2)o;
             // 其他使用 b 的部分
         }
         else
         {
             Console.WriteLine("o 不屬於 MyClass1 也不屬於 MyClass2");
         }
     }
     static void Main(string[] args)
     {
         MyClass1 c1 = new MyClass1();
         MyClass2 c2 = new MyClass2();
         Test(c1);
         Test(c2);
         Test("嘎~隨便一個字串");

         // 停下來看結果
         Console.ReadLine();
     }
 }

is 範例檔
</s

正在載入...

發佈於 2008/05/292012/05/08作者 fredxxx123分類 C#, C++, 程 - 式 - 設 - 計


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK