【发布时间】:2010-11-02 16:22:03
【问题描述】:
我试图弄清楚如何在 F# 中的类中创建静态方法。有谁知道如何做到这一点?
【问题讨论】:
-
不要忘记在线文档! Methods 有此信息,F# Language Reference 是查找有关语言语法信息的一般良好起点。
我试图弄清楚如何在 F# 中的类中创建静态方法。有谁知道如何做到这一点?
【问题讨论】:
当然,只需在方法前加上 static 关键字。这是一个例子:
type Example = class
static member Add a b = a + b
end
Example.Add 1 2
val it : int = 3
【讨论】:
如果你想在静态类中拥有静态方法,那么使用模块
查看此链接,尤其是模块部分:
http://fsharpforfunandprofit.com/posts/organizing-functions/
这是一个包含两个函数的模块:
module MathStuff =
let add x y = x + y
let subtract x y = x - y
在幕后,F# 编译器使用静态方法创建一个静态类。所以 C# 相当于:
static class MathStuff
{
static public int add(int x, int y)
{
return x + y;
}
static public int subtract(int x, int y)
{
return x - y;
}
}
【讨论】: