向现有类型添加新方法属性
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