Classes without constructor in F#

江枫思渺然 提交于 2019-12-12 10:43:33

问题


I'm not sure why F# seems to allow the definition of a class without any constructors. I mean, it would be impossible to instantiate an object of the class. Shouldn't the language spec treat this as illegal behavior?

For example, I can define the class

type myClass =
    class
        member this.x = 0
    end

myClass seems to have the type

type myClass =
    member x: int

But it would not be instantiable.


回答1:


In my experience, the object-oriented features of F# can sometimes be less elegant than what C# enables you to express. The above question could be one example; another example is automatically implemented mutable properties.

Most people (including me) seem not to care, because we rarely use those features. The object-oriented features of F# mainly exist in order to enable interoperation with other .NET code, so while they can be useful, they aren't the important parts of the language. My guess is that no one thought of implementing that compiler check because it wouldn't provide much value. As soon as you'd attempt to use myClass, you'd notice that something was wrong.




回答2:


When you create a class with no constructors (in other words, a class that can't be instantiated) you are basically creating an static class*.

In C# you can use the static keyword to allow the compiler to check if you have instance members or not. In F# you don't have such check in compile time.

* Sort of. The proper definition of a static class is one that can't be instantiated or inherited and only has static methods.



来源:https://stackoverflow.com/questions/33014900/classes-without-constructor-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!