灵活的类型标注在F#的目的是什么? [英] What is the purpose of flexible type annotation in F#?

查看:125
本文介绍了灵活的类型标注在F#的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习F#,我不明白灵活的类型,或者更好的目的,我不明白写这之间的区别:

I'm studying F# and I don't understand the purpose of flexible types, or better, I can't understand the difference between writing this:

set TextOfControl (c : Control) s = c.Text <- s

和写的:

set TextOfControl (c : 'T when 'T :> Control) s = c.Text <- s

其中,控制 System.Windows.Forms.Control的类。

推荐答案

。在你的例子没有什么区别。如果返回类型的限制,你开始看到的区别:

There is no difference in your example. If return types are constrained, you start seeing the difference:

let setText (c: Control) s = c.Text <- s; c
let setTextGeneric (c: #Control) s = c.Text <- s; c

let c = setText (TreeView()) "" // return a Control object
let tv = setTextGeneric (TreeView()) "" // return a TreeView object

注意 #Control 的快捷键T时,'T:&GT;控制类型约束是很重要的子类型创建通用的功能。

Note that #Control is a shortcut of 'T when 'T :> Control. Type constraints are important to create generic functions for subtypes.

例如,

let create (f: _ -> Control) = f()

let c = create (fun () -> Control()) // works
let tv = create (fun () -> TreeView()) // fails

VS

let create (f: _ -> #Control) = f()

let c = create (fun () -> Control()) // works
let tv = create (fun () -> TreeView()) // works

这篇关于灵活的类型标注在F#的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆