向現有型別新增新方法屬性
F#允許在定義型別時將函式作為成員新增到型別中(例如,記錄型別 )。但是,F#還允許將新例項成員新增到現有型別 - 甚至是在其他地方和其他 .net 語言中宣告的型別。
以下示例將新例項方法 Duplicate
新增到 String
的所有例項中。
type System.String with
member this.Duplicate times =
Array.init times (fun _ -> this)
注意 :this
是一個任意選擇的變數名,用於引用正在擴充套件的型別的例項 - x
也可以正常工作,但可能不那麼自我描述。
然後可以通過以下方式呼叫它。
// F#-style call
let result1 = "Hi there!".Duplicate 3
// C#-style call
let result2 = "Hi there!".Duplicate(3)
// Both result in three "Hi there!" strings in an array
此功能與 C#中的擴充套件方法非常相似。
新屬性也可以以相同的方式新增到現有型別。如果新成員不帶引數,它們將自動成為屬性。
type System.String with
member this.WordCount =
' ' // Space character
|> Array.singleton
|> fun xs -> this.Split(xs, StringSplitOptions.RemoveEmptyEntries)
|> Array.length
let result = "This is an example".WordCount
// result is 4