F#:使用和不使用括号定义的类型之间的差异

时间:2016-07-10 09:24:10

标签: f#

F#中type Something()type Something之间有什么区别?

为什么ASP.NET Core 1.0 F# project中引用的此代码段有效:

open System
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Http

type Startup() = 
    member this.Configure(app: IApplicationBuilder) =
      app.Run(fun context -> context.Response.WriteAsync("Hello from ASP.NET Core!"))

[<EntryPoint>]
let main argv = 
    let host = WebHostBuilder().UseKestrel().UseStartup<Startup>().Build()
    host.Run()
    printfn "Server finished!"
    0

但这失败了:

open System
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Http

type Startup = 
    member this.Configure(app: IApplicationBuilder) =
      app.Run(fun context -> context.Response.WriteAsync("Hello from ASP.NET Core!"))

[<EntryPoint>]
let main argv = 
    let host = WebHostBuilder().UseKestrel().UseStartup<Startup>().Build()
    host.Run()
    printfn "Server finished!"
    0

1 个答案:

答案 0 :(得分:7)

您可以通过在F#Interactive中输入它来看到差异:

type Parens() =
    member this.add10 x = x + 10

type NoParens =
    member this.add10 x = x + 10;;

输出:

type Parens =
  class
    new : unit -> Parens
    member add10 : x:int -> int
  end
type NoParens =
  class
    member add10 : x:int -> int
  end

第二个类没有定义构造函数。编译器不应该允许的东西,但出于某种原因。它不会生成像C#这样的自动构造函数。

有关详情,请查看classesinterfaces F#的有趣和利润页面。另请查看此StackOverflow post

并且为了将来参考,当有疑问时,打开F#interactive,输入你想要看到的两个东西,并比较输出。它是一个强大的工具,您应该使用它。