MiP*_*MiP 3 .net f# functional-programming casting language-design
例如,如果我尝试扩展int,而int不是该类型的真实名称,则此代码将失败:
type int with
member this.IsEven = this % 2 = 0
Run Code Online (Sandbox Code Playgroud)
我必须System.Int32改用:
type System.Int32 with
member this.IsEven = this % 2 = 0
//test
let i = 20
if i.IsEven then printfn "'%i' is even" i
Run Code Online (Sandbox Code Playgroud)
为什么我不能使用类型缩写int?
我认为Will的滑稽答案基本上是正确的 - 默认情况下功能未实现.但是,另一个可能的原因是类型缩写是作用域的,因此缩写的范围是否应该影响扩展的范围并不是很明显.例如:
module X =
type t = int
module Y =
// imagine we could hypothetically do this
type X.t with
member i.IsEven = i % 2 = 0
open Y
fun (x:System.Int32) -> x.IsEven // should this compile even though t isn't in scope here?
Run Code Online (Sandbox Code Playgroud)