【问题标题】:F# Static Methods In Class类中的 F# 静态方法
【发布时间】:2010-11-02 16:22:03
【问题描述】:

我试图弄清楚如何在 F# 中的类中创建静态方法。有谁知道如何做到这一点?

【问题讨论】:

标签: f# static function class


【解决方案1】:

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

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

val it : int = 3

【讨论】:

  • 如果你能用简单的语法更新你的答案会很棒(所以,不需要使用“end”关键字)
【解决方案2】:

如果你想在静态类中拥有静态方法,那么使用模块

查看此链接,尤其是模块部分:

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;
    }
}

【讨论】:

  • 但接受的答案表明类中的静态成员是可能的。这个实现细节似乎与问题不太相关。
  • 既然可以使用模块,为什么还要使用类型?我更喜欢这个答案
  • 这可能不是“正确”的答案,但它是一个有用的答案。
猜你喜欢
  • 2010-11-04
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 2012-10-17
  • 2012-06-24
  • 1970-01-01
相关资源
最近更新 更多