【发布时间】:2014-03-25 00:14:00
【问题描述】:
我认为 F# 函数和 System.Func 之间的转换必须手动完成,但似乎存在编译器(有时)为您执行此操作的情况。当它出错时,错误信息不准确:
module Foo =
let dict = new System.Collections.Generic.Dictionary<string, System.Func<obj,obj>>()
let f (x:obj) = x
do
// Question 1: why does this compile without explicit type conversion?
dict.["foo"] <- fun (x:obj) -> x
// Question 2: given that the above line compiles, why does this fail?
dict.["bar"] <- f
最后一行编译失败,报错:
This expression was expected to have type
System.Func<obj,obj>
but here has type
'a -> obj
显然函数f 没有'a > obj 的签名。如果 F# 3.1 编译器对第一个字典赋值感到满意,那么为什么不对第二个赋值呢?
【问题讨论】:
-
我猜这是一种转换不是自动的情况,但错误不是很有帮助,但在技术上可能仍然是正确的。
-
我猜只有 lambda 会自动转换。
-
@MisterMetaphor:正确:stackoverflow.com/questions/3392000/…
-
但是,等等,为什么
f和fun (x:obj) -> x的类型不一样?升级到f : 'a -> obj是怎么回事?
标签: f#