我在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))