在F#中定义静态类 [英] Defining static classes in F#
问题描述
是否可以在F#中定义一个包含可重载成员的静态类? let
模块绑定不能重载,即使它们已被编译为静态类中的静态静态成员.
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 static static members in static classes.
type
碎片可以包含静态成员,但是我不知道类型本身是否可以设置为静态.
type
declerations can contain static members, but I don't know if the type itself can be made static.
我当前的解决方案是使用私有构造函数定义type
并使用它.我想知道是否有一种方法可以根据需要定义静态类型.
My current solution is to define a type
with a private constructor and just use that. I'm wondering if there is a way I can define a static type as I want.
推荐答案
正如罗伯特·杰普森(Robert Jeppeson)所指出的那样,C#中的静态类"只是创建不能实例化或继承的类的简写.静态成员.这是您可以在F#中完全实现的方法:
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#:
[<AbstractClass; Sealed>]
type MyStaticClass private () =
static member SomeStaticMethod(a, b, c) =
(a + b + c)
static member SomeStaticMethod(a, b, c, d) =
(a + b + c + d)
这可能有点矫kill过正,因为AbstractClass
和私有构造函数都将阻止您创建该类的实例,但是,这是C#静态类的作用-将它们编译为抽象类与私有的构造函数. Sealed
属性可防止您从此类继承.
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.
如果您像在C#中那样添加实例方法,则该技术不会导致编译器错误,但是从调用者的角度来看,没有区别.
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.
这篇关于在F#中定义静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!