4

我在 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 |]它可以工作(但当然只有一个按钮)。

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

4

1 回答 1

3

在这种情况下更容易使用序列。您可以使用以下功能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))
于 2015-05-18T14:08:49.270 回答