Fork me on GitHub

12/21/2009

[C# 筆記] Polymorphic 多型

  • 當 base class 定義了一個 public method,所有的子類別分支(相關型別) 對於這個方法的反應都是一樣的。如何使相關型別對於同一個 request 做出不同的 respond 就是多形所要探討的。
  • virtual and override Keywords
    • 若一 base class 希望當中定義的 method 可以(may be)被覆寫,那麼就要使用 "virtual";若一子類別要覆寫 base class 的 virtual method 的話,則要加上 "override"。
    • 在 overriden method 當中不一定要全部重新定義,可以透過 "base" 來存取原 base class 的功能。
  • Sealing Virtual Members
    • 有時候只是想把 class 當中的某個 virtual method 給 seal 起來,讓子類別無法進行覆寫,而非對整個 class seal。這時候可以針對 virtual method 下 "sealed" Keyword
  • Abstract Classes
    • base class 通常定義一般性的物件元素,創建 base class 的物件通常不具有太大的意義,因此可以透過 "abstract" 來避免針對 base class 進行物件的創建。
    • 在 abstract class 當中,可以定義 abstract member,這種 member 可以完全不定義其 default implementation (不同於 viutual)。因此你強迫了每一個繼承此類別的子類別自行定義該方法之實做。
  • Member Shadowing
    • 假若子類別定義了一個和父類別一模一樣的成員,那麼子類別的版本會覆蓋父類別的版本。
    • 當你從外部取得一個類別,而要將此外部類別融入你的 base class 的時候,就可能會發生 member shadowing 的情形。這時候會得到一個 warning,有兩種解決方式。一、返回 base class 將被 shadow 的 method 加上 "virtual"。二、針對該子類別的 shadowing method 加上 "new",意味著覆蓋所有在此之前的版本。
  • Base Class/Derived Class Casting Rules
    • 用 base class type 宣告的陣列當中可以放其子類別創建的物件(implicit cast)。it is always safe to store a derived type within a base class reference (e.g. baseclass A = new derived ();) 。
    • 這麼做的好處是當你定義一個方法的輸入參數為 base class reference,那麼你就可以傳遞所有 derived class 的物件到這個方法當中。
    • 除了 implicit cast 還可以直接用  explicit cast 硬轉,但是不是每種狀況都可以硬轉,C# 提供 "as" Keyword 讓你檢查兩個物件的 compatability。
    • Hexagon hex = (Hexagon)frank;
      Hexagon hex2 = frank as Hexagon;
      if (hex2 == null)
      Console.WriteLine("Sorry, frank is not a Hexagon...");
    • 第二點當中的方法要怎麼知道丟進來的物件是哪一個 derived type 來做相對應的處理(知道是哪一個derived type 之後再用 explicit cast) 呢? C# 提供 "is" Keyword 和 "as" 相似,只是如果兩個物件 incompatable 的話 "as" 會返回 null, "is" 會返回 false。

No comments:

Post a Comment