F#中的静态方法

RCI*_*CIX 13 f# static class function

我试图弄清楚如何在F#中的类中创建静态方法.有谁知道怎么做?

ske*_*ker 27

当然,只需在方法前加上static关键字.这是一个例子:

type Example = class
  static member Add a b = a + b
end
Example.Add 1 2

val it : int = 3
Run Code Online (Sandbox Code Playgroud)


xx1*_*1xx 6

如果您想在静态类中使用静态方法,请使用Module

查看此链接,特别是模块部分:

http://fsharpforfunandprofit.com/posts/organizing-functions/

这是一个包含两个函数的模块:

module MathStuff = 

    let add x y  = x + y
    let subtract x y  = x - y
Run Code Online (Sandbox Code Playgroud)

在幕后,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;
    }
}
Run Code Online (Sandbox Code Playgroud)