首页 / 操作系统 / Linux / F# 4.1提供改善,并支持与C# 7的互操作
F# 4.1对语言进行了很多改进。F# 4.1将通过新版本的Microsoft tools for F#提供,Microsoft tools for F#据说将于今年晚些时候发布。该版本支持结构体元组(struct tuples),与C# 7的互操作,以及by-ref返回。由于F#的语法和类型推断简化了元组的使用,元组通常在F#中使用。它们是存储在堆栈上的引用类型。F# 4.1中提供了存储在堆栈上的结构体元组。对于某些场景来说,性能得到了提升,比如说需要分配大量的小元组。要支持ValueTuple类型,元组类型、元组表达式和元组模式可以用关键字struct来注释。// Creating a new struct tuple.let origin = struct (0, 0)// Take struct tuples as arguments to a function and generate a new struct tuple.let getPointFromOffset (point: struct (x, y)) (offset: struct (dx, dy)) = struct (x + dx, y + dy)// Pattern match on a struct tuple.let doAMatch (input: struct (x, y)) =match input with| struct (0, 0) -> sprintf "The tuple is the origin!"| struct (_, _) -> sprintf "The tuple is NOT the origin!"
与C# 7的互操作也支持使用struct关键字。// Calls a C# function returning a value tuplelet struct(word, value) = SomeService.SomeResult()// Calls a C# function taking a value tuple in parameter.let result = SomeService.CreateResult(struct("hello", 12))
除了元组之外,记录类型和可区分联合也可以表示为值类型。它需要struct注释。 [<Struct>] type Student = {Id: intName: stringAge: intGPA: doubleMajor: string}[<Struct>]type Shape = | Circle of radius: float| Square of side: int| Rectangle of sides: double*double
F# 4.1也提供by-ref返回。F#已经支持了ref locals,但是不支持使用或生成byref-returning方法。// Returns from an array.let f (x:int[]) = &x.[0]// Returns from a record[<Struct>]type R = { mutable z : int }let f (x:byref<R>) = &x.z
by-ref返回也可以在C#的方法中使用。public static ref int Find(int val, int[] vals){for (int i = 0; i < vals.Length; i++){if (vals[i] == val){return ref numbers[i];}}}// "result" is of type "byref<int>".let result = SomeCSharpClass.Find(3, [| 1; 2; 3; 4; 5 |])
除了GitHub上公布的F#源代码,你也可以参考公开的语言规范获取更多信息。查看英文原文:F# 4.1 Brings Improvements and Interoperation with C# 7本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-02/140297.htm