在F#中使用Windows窗体的面向对象的"Hello world"

Sim*_*ard 6 f# winforms

我目前正在通过"真实世界的功能编程".我试图让1.12工作,一个使用Windows窗体的"hello world"程序.这是代码: -

    open System.Drawing;;
    open System.Windows.Forms;;

    type HelloWindow() =
         let frm = new Form(Width = 400, Height = 140)
         let fnt = new Font("Times New Roman", 28.0f)
         let lbl = new Label(Dock = DockStyle.Fill, Font = fnt,
                               TextAlign = ContentAlignment.MiddleCenter)
         do frm.Controls.Add(lbl)


         member x.SayHello(name) =
              let msg = "Hello" + name + "!"
              lbl.Text <- msg

         member x.Run() =
              Application.Run(frm);;

    let hello = new HelloWindow();;
    hello.SayHello("you");;
    hello.Run();;
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会引发错误 - "在单个线程上启动第二个消息循环不是有效的操作." 显然,有一个窗口打开而不是终止,这使程序混乱.我看不出如何修复错误,任何人都可以帮助我吗?

我也尝试输入最终的代码块: -

    let hello = new HelloWindow()
    hello.SayHello("you")
    hello.Run();;
Run Code Online (Sandbox Code Playgroud)

但这没有用.代码运行正常但没有结果,最后一行被注释掉了.

pad*_*pad 6

该示例旨在编译并作为Windows窗体应用程序运行.如果您想在F#Interactive中运行它,则必须使用frm.Show()而不是Application.Run(frm).

您可以使用编译器指令使示例在F#Interactive和编译项目中都起作用:

type HelloWindow() =
    let frm = new Form(Width = 400, Height = 140)
    // ...
    // The same as before

    member x.Run() =
        #if INTERACTIVE
        frm.Show()
        #else
        Application.Run(frm)
        #endif
Run Code Online (Sandbox Code Playgroud)