gpt4 book ai didi

f# - F# 中的通用模块

转载 作者:行者123 更新时间:2023-12-04 13:55:55 24 4
gpt4 key购买 nike

在 C# 中,我可以编译

static class Foo<T> { /* static members that use T */ }

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

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

最佳答案

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

type Foo<'a> private() =          // '
static member Blah (a:'a) = // '
printfn "%A" a

是很棒的。忽略 Reflector 生成的内容,您无法从 F# 程序集中实例化此类(因为构造函数是私有(private)的),因此效果很好。

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"

关于f# - F# 中的通用模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1211847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com