Defining static classes in F#

后端 未结 5 718
故里飘歌
故里飘歌 2021-02-12 03:56

Is it possible to define a static class that contains overloadable members in F#? let module bindings cannot be overloaded, even though they are compiled into stati

5条回答
  •  温柔的废话
    2021-02-12 04:02

    As Robert Jeppeson pointed out, a "static class" in C# is just short-hand for making a class that cannot be instantiated or inherited from, and has only static members. Here's how you can accomplish exactly that in F#:

    []
    type MyStaticClass private () =
        static member SomeStaticMethod(a, b, c) =
           (a + b + c)
    
        static member SomeStaticMethod(a, b, c, d) =
           (a + b + c + d)
    

    This might be a little bit of overkill, as both the AbstractClass and the private constructor will prevent you from creating an instance of the class, however, this is what C# static classes do - they are compiled to an abstract class with a private constructor. The Sealed attribute prevents you from inheriting from this class.

    This technique won't cause a compiler error if you add instance methods the way it would in C#, but from a caller's point of view there is no difference.

提交回复
热议问题