F# 是否继承了 Object 的所有类型?
问题很简单并且。尽管答案很明显,但我不得不面对一种奇怪的情况,其中 fsharp 告诉我一些有点奇怪的事情。故事是这样的:
问题是:F# 是否会自动使每种类型继承 Object
类?我想是的,而且我确信这一点,因为如果不是这样的话,将会有很多并发症。
但这是一个事实。 我正在写这段代码:
type MyType =
val myval: int
override self.ToString = "Hello MyType"
嗯,fsharp 编译器告诉我使用 override 是不正确的,因为他没有找到任何名为 ToString
的方法来重写。我这样编译了这段代码:
type MyType =
val myval: int
member self.ToString = "Hello MyType"
一切正常。 嗯嗯发生了什么事??? FSharp 不是应该从 Object
继承每个对象吗?
The question is simple and. although it is obvious the answer, I had to face a strange situation where the fsharp told me something a bit strange. Here's the story:
The question is: Does F# automatically make every type inherit the Object
class? I suppose YES and I am certain of this because there would be so many complications if that were not the case.
But here's a fact.
I was writing this piece of code:
type MyType =
val myval: int
override self.ToString = "Hello MyType"
Well, fsharp compiler told me it is not correct using overrid because he does not find any method called ToString
to override. I so compiled this code:
type MyType =
val myval: int
member self.ToString = "Hello MyType"
And everything worked fine.
mmmmmm What's happening???
Isn't FSharp supposed to inherit every object from Object
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您忘记了括号:
在省略括号的原始代码中,您试图覆盖属性 ToString。
You forgot parens:
In your original code with parens omitted you were trying to override property ToString.
德斯科已经用你的代码片段解释了这个问题。
F# 的行为与 C# 类似,这意味着所有类型都继承自
Object
,尽管值类型的行为略有微妙。当您拥有值类型的变量时,不能将其直接视为Object
,而是需要装箱(转换为继承自Object
的 .NET 引用类型)。这可能会导致类型推断出现一些令人困惑的错误:
当您编写此代码时,您会收到一条错误消息:
如果严格意义上从
Object
继承的所有内容,那么 F# 编译器应该能够将任何类型参数转换为Object
,但这是不允许的。问题是值类型需要装箱,因此您需要编写match box x with ...
。Desco already explained the probelm with your snippet.
F# behaves just like C#, which means that all types inherit from
Object
, although with a slightly subtle behavior of value types. When you have a variable of a value type, it cannot be directly treated asObject
and need to be boxed (to a .NET reference type that inherits fromObject
).This can cause some confusing errors with type inference:
When you write this, you get an error message:
If everything inherited from
Object
in the strict sense, then F# compiler should be able to convert any type parameter toObject
, but that's not allowed. The problem is that value types need boxing, so you need to writematch box x with ...
.不。有些类型不是从对象派生的。例如,接口是不从对象派生的类型。请参阅 http:// blogs.msdn.com/b/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx 了解更多详细信息。
No. There are types that do not derive from object. Interfaces, for example, are types that do not derive from object. See http://blogs.msdn.com/b/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx for more detail.