【发布时间】:2023-04-07 22:26:01
【问题描述】:
我正在查看此处描述的 F# 中类型的模式匹配语法:
http://msdn.microsoft.com/de-de/library/dd547125.aspx#sectionToggle14
该页面的示例(稍作修改):
open System.Windows.Forms
let RegisterControl (control: Control) =
match control with
| :? Button as button -> button.Text <- "Registered."
| :? CheckBox as checkbox -> checkbox.Checked <- false
| _ -> ()
我不明白为什么我们需要在类型检查的同时引入一个新名称(“按钮”、“复选框”)。如果匹配成功,编译器应该知道“控制”具有所需的类型,并且可以在以下表达式/语句中相应地处理它。换句话说,为什么我不能这样做:
open System.Windows.Forms
let RegisterControl (control: Control) =
match control with
| :? Button -> control.Text <- "Registered."
| :? CheckBox -> control.Checked <- false
| _ -> ()
这类似于"type guard" feature in TypeScript 1.4。
F# [还] 不这样做有充分的理由吗? (注意:我正在运行 VS 2012。)
【问题讨论】:
标签: .net f# pattern-matching