开发者

Let and Property Assignment in one line

How can you write the following F# code (or si开发者_运维百科milar) in one line:

let contextMenu = new ContextMenuStrip()
mainForm.ContextMenuStrip <- contextMenu

I have to declare contextMenu as it will be needed later.


I don't recommand you to write it on a single line because this means it will be a mix between the #light (the mode by default now) and non #light syntax. If you really need to, you can use ;; like that:

open System
open System.Windows.Forms

let mainForm = new Form()
let contextMenu = new ContextMenuStrip();; mainForm.ContextMenuStrip <- contextMenu;;

If your expressions have unit type you can use a Sequential Execution Expression, which is an expression of the form:

expr1; expr2; expr3

for instance:

mainForm.ContextMenuStrip <- contextMenu; 5 + 6 |> ignore; mainForm.ContextMenuStrip <- null

I'd like to add that Sequential Execution Expressions have nothing to do with the non #light mode. They are just a general language construct.

Hope it helps.


You can set public, writeable properties as pseudo-parameters in the constructor.

let contextMenu = new ContextMenuStrip()
let form = new Form(ContextMenuStrip = contextMenu)


You could also type

let contextMenu = new ContextMenuStrip() in mainForm.ContextMenuStrip <- contextMenu

This is OCaml syntax, IIRC.

Edit: to be more clear: this is also valid (#light) F# syntax, since F# is based on OCaml.

I also don't recommend doing this, even though I like short programs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜