我更喜欢按照 F# 的习惯将函数与类型分开:
[<Struct>]
type Vec2 =
{
x : single
y : single
}
static member inline (/) (v, scalar) =
let s = single scalar in { x = v.x / s; y = v.y / s }
[<CompilationRepresentation (CompilationRepresentationFlags.ModuleSuffix)>]
module Vec2 =
let inline length v = ((pown v.x 2) + (pown v.y 2)) |> sqrt
let unit v = let l = length v in { x = v.x / l; y = v.y / l }
不幸的是,在 C# 中,length
和 unit
函数是 Vec2Module.length
和 Vec2Module.unit
。 恶心。
除了将函数定义为 Vec2
的静态成员外,还有什么解决方法?
更新:
感谢您的回复,这是很好的解决方案,解决了 Module
后缀的局限性。
我不想为每个以这种方式编写的模块都进行显式声明,所以我将坚持使用静态成员方法而不是 let
中的绑定(bind)定义模块。
顺便说一句,我想知道 future 的 C# 版本是否已考虑到这一点。例如当用属性修饰类型、方法、属性等时,省略 Attribute
后缀始终是可以接受的。也许在某些时候,Module
后缀会发生类似的事情?
最佳答案
在 C# 6.0 中你可以 access static members without specifying a type name .在你的情况下:
using static Vec2Module;
关于c# - 从没有丑陋的 "Module"后缀的 C# 调用 F# 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50899592/