簡體   English   中英

(Clojure的)多方法和(C#)擴展方法之間的區別?

[英]Difference between (Clojure's) multimethod and (C#'s) extension methods?

我剛剛觀看了Clojure中有關協議的視頻,並解釋了“多方法”的工作原理。 在我看來,它們看起來非常類似於C#中的擴展方法。 它們基本上是一回事(除了您不需要在Clojure中創建靜態類)或者是否存在根本區別? 使用任何一種都有優勢或劣勢嗎?

Clojure中的mutlimethod功能適用於多個調度方案。 它有效地啟用了運行時多態,其中調用的方法取決於方法的參數類型(傳統的單調度多態性取決於接收方法調用的對象的運行時類型)。 基本上,您可以將單調度多態性視為方法M

M(arg1, arg2, arg3, ..., argn)

並且調用的實際方法取決於arg1的運行時類型(因此我們正在重寫通常的語法

arg1.M(arg2, arg3, ..., argn)

M(arg1, arg2, arg3, ..., argn)

使類比清楚。 在多個分派中,由...調用的方法

M(arg1, arg2, arg3, ..., argn)

取決於arg1arg2 ,..., argn的運行時類型。

您可以在C#中使用dynamic 實現類似的功能。

坦率地說,它根本與擴展方法無關。

Clojure multimethods設計用於完全動態調度 - 即您可以在參數的任意函數的基礎上選擇函數的實現。

調度計算屬性的示例:

(def stone {:name "stone" :weight 1000})

(def feather {:name "feather" :weight 1})

;; dispatch function - can be any function
(defn heaviness [thing]
  (if (> (:weight thing) 100)
    "Heavy"
    "Not heavy"))

;; multimethod definition using the given dispatch function
(defmulti lift heaviness)

;; implementation of two alternative methods based
(defmethod lift "Heavy" 
  (fn [thing] 
    (str "Trying to lift a heavy " (:name thing))))

(defmethod lift "Not heavy" 
  (fn [thing] 
    (str "Easily lifting a light " (:name thing))))

(lift stone)
=> "Trying to lift a heavy stone"

(lift feather)
=> "Easily lifting a light feather"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM