F#中的通用模块

Gab*_*iel 6 generics f# module

在C#中,我可以编译

static class Foo<T> { /* static members that use T */ }
Run Code Online (Sandbox Code Playgroud)

结果是通用的,不可实例化.

什么是等效的F#代码? module<'a>不编译,type Foo<'a>可以实例化.

Bri*_*ian 9

到目前为止,其他答案都有部分图片......

type Foo<'a> private() =          // '
    static member Blah (a:'a) =   // '
        printfn "%A" a
Run Code Online (Sandbox Code Playgroud)

是很棒的.忽略Reflector生成的内容,你不能在F#程序集中实例化这个类(因为构造函数是私有的),所以这很好用.

F#也允许使用静态构造函数,语法是在类中包含'static let'和'static do'语句(类似于'let'和'do'如何作为实例的主构造函数体的一部分工作) .一个完整的例子:

type Foo<'a> private() =             // '
    static let x = 0
    static do printfn "Static constructor: %d" x
    static member Blah (a:'a) =      // '
        printfn "%A" a

//let r = new Foo<int>() // illegal
printfn "Here we go!"
Foo<int>.Blah 42
Foo<string>.Blah "hi"
Run Code Online (Sandbox Code Playgroud)

  • 喜欢//'技巧将从现在开始做到这一点 (4认同)