简体   繁体   English

F#中没有构造函数的类

[英]Classes without constructor in F#

I'm not sure why F# seems to allow the definition of a class without any constructors. 我不确定为什么F#似乎允许在没有任何构造函数的情况下定义类。 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 myClass似乎有类型

type myClass =
    member x: int

But it would not be instantiable. 但它不可实现。

In my experience, the object-oriented features of F# can sometimes be less elegant than what C# enables you to express. 根据我的经验,F#的面向对象特性有时不如C#表达的优雅。 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. F#的面向对象特性主要用于实现与其他.NET代码的互操作,因此虽然它们很有用,但它们并不是语言的重要组成部分。 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. 一旦你尝试使用myClass ,你就会注意到出了什么问题。

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. 在C#中,您可以使用static关键字来允许编译器检查您是否有实例成员。 In F# you don't have such check in compile time. 在F#中,您没有在编译时进行此类检查。

* Sort of. * 有点。 The proper definition of a static class is one that can't be instantiated or inherited and only has static methods. 静态类的正确定义是无法实例化或继承的,只有静态方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM