Tuple.Create in F#

时间:2014-12-01 16:27:00

标签: .net f# tuples base-class-library

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

1 个答案:

答案 0 :(得分:6)

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

您可以在F# spec

中找到详细说明

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>  

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