Extension methods for specific generic types

a 夏天 提交于 2019-12-05 01:28:08
kvb

This isn't possible in the current version of F#, unfortunately. See related question here.

Generic extension methods are now available in F# 3.1:

open System.Runtime.CompilerServices
open System.Collections.Generic

[<Extension>]
type Utils () =
    [<Extension>]
    static member inline Abc(obj: IEnumerable<int>) = obj.ToString()

printfn "%A" ([1..10].Abc())

Well, you can use constraints - but not with sealed types like int.

type IEnumerable<'a when 'a :> InheritableType> =
member this.Blah =
    this.ToString()

Hmm...

In order to help others looking for similar solutions, here is an example showing how to use generic extension methods with type constraints. In the example below, there is a type constraint requiring that the type argument passed exposes a default constructor. This is done using the [<CLIMutable>] attribute applied to the Order record. Also, I'm constraing the result of the method to the type passed.

In order to use the extension method you have to specify the type you want to use. Note that I'm also extending a generic dictionary interface.

[<Extension>]
type ExtensionMethds () = 

    [<Extension>]
    static member inline toObject<'T when 'T: (new: unit -> 'T)> (dic: IDictionary<string,obj>): 'T =
        let instance = new 'T()
        // todo: set properties via reflection using the dictionary passed in
        instance


[<CLIMutable>]
type Order = {id: int}

let usage = 
    let dictionaryWithDataFromDb = dict ["id","1" :> obj] 
    let theOrder = dictionaryWithDataFromDb.toObject<Order>()
    theOrder
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!