Tuple.Create in F#

Ove*_*ive 4 .net f# tuples base-class-library

我注意到System.Tuple.CreateF#中方法的一个非常奇怪的行为.查看MSDN文档时,它表明返回类型是System.Tuple<T>.但是在F#中使用此方法时除了Tuple.Create(T)将返回所有重载'T1 * 'T2.显然调用Tuple<T>构造函数将返回Tuple<T>.但我不明白Tuple.CreateF#的返回类型是如何不同的.

Gus*_*Gus 6

元组类型的F#(一个语法元组)编译为System.Tuple<..>.因此它们在.NET级别是相同的类型,但对于F#类型系统,它们是不同的类型:语法元组的类型与a的类型不匹配,System.Tuple<..>但它们的运行时类型将是相同的.

您可以在F#规范中找到详细说明

这个例子new System.Tuple<'t>()没有返回一个语法元组,可能是因为你明确地实例化了一个特定的类型,你应该回过头来.

以下是一些测试:

let x = new System.Tuple<_,_>(2,3) // Creates a Tuple<int,int>
let y = System.Tuple.Create(2,3)   // Creates a syntactic tuple int * int

let areEqual = x.GetType() = y.GetType() // true

let f (x:System.Tuple<int,int>) = ()
let g (x:int * int) = ()

let a = f x
let b = g y

// but

let c = f y 
//error FS0001: The type 'int * int' is not compatible with the type 'Tuple<int,int>'

let d = g x
// error FS0001: This expression was expected to have type int * int but here has type Tuple<int,int>  
Run Code Online (Sandbox Code Playgroud)

因此,在编译时它们是不同的,但在运行时它们是相同的.这就是为什么当你使用.GetType()时得到相同的结果.