F# 将按钮列表添加到表单控件范围

F# add a list of buttons to a form control range

我在 F# 中创建了以下代码:

open System.Drawing
open System.Windows.Forms

let form = new Form(Text="project", TopMost=true, Width=400, Height=400)

let defaultSize = new Size(20,20)

let buttonPos text x y = new Button(Text=text, Top=x, Left=y, Size=defaultSize, BackColor=Color.Aqua)

let gameButtons = [for y in 1..9 do for x in 1..9 -> (buttonPos "X" (x*10) (y*10))]

form.Controls.AddRange (List.toArray(gameButtons))

我收到错误:Error 1 Type mismatch. Expecting a Control list but given a Button list. The type 'Control' does not match the type 'Button'.

我也尝试过将 gameButtons 创建为数组:

let gameButtons = [|for y in 1..9 do for x in 1..9 -> (buttonPos "X" (x*10) (y*10))|]
form.Controls.AddRange gameButtons

但这导致了错误:Error 1 Type mismatch. Expecting a Control [] but given a Button [] The type 'Control' does not match the type 'Button'

如果我将 gameButtons 作为列表并写入 form.Controls.AddRange [| gameButtons.Head |] 它会起作用(但当然只有一个按钮)。

所以我的问题是,为什么我不能像这样添加控件?我怎样才能将所有按钮添加到范围中?

在这种情况下使用序列更容易。您可以使用函数 Seq.cast :

open System.Drawing
open System.Windows.Forms

let form = new Form(Text="project", TopMost=true, Width=400, Height=400)

let defaultSize = new Size(20,20)

let buttonPos text x y = new Button(Text=text, Top=x, Left=y, Size=defaultSize, BackColor=Color.Aqua)

let gameButtons = seq{ for y in 1..9 do for x in 1..9 -> (buttonPos "X" (x*10) (y*10)) } |> Seq.cast<Control>

form.Controls.AddRange (Seq.toArray(gameButtons))