代码之家  ›  专栏  ›  技术社区  ›  Noldorin

特定泛型类型的扩展方法

  •  8
  • Noldorin  · 技术社区  · 16 年前

    我正在尝试为泛型类型创建各种扩展方法 绑定到特定泛型类型参数 在F#中,但语言似乎不允许我:

    type IEnumerable<int> with
        member this.foo =
            this.ToString()
    

    但它给了我编译器错误(在 int 关键词):

    类型名称中存在意外标识符。应为中缀运算符、引号符号或其他标记。

    以下 虽然它没有将泛型类型参数专门绑定到 int ,正如我所想:

    type IEnumerable<'a> with
        member this.foo =
            this.ToString()
    

    4 回复  |  直到 16 年前
        1
  •  8
  •   Community Mohan Dere    8 年前

    不幸的是,这在当前版本的F#中是不可能的。见相关问题 here .

        2
  •  9
  •   dharmatech    12 年前

    通用扩展方法现已在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())
    
        3
  •  0
  •   Massif    16 年前

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

    隐马尔可夫模型。。。

        4
  •  0
  •   Mário Meyrelles    9 年前

    为了帮助其他人寻找类似的解决方案,下面的示例演示了如何使用带有类型约束的泛型扩展方法。在下面的示例中,有一个类型约束要求传递的类型参数公开默认构造函数。这是使用 [<CLIMutable>] 应用于 Order 记录。此外,我还将方法的结果约束为传递的类型。

    [<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