我認爲F#函數和System.Func之間的轉換必須手動完成,但似乎有編譯器(有時)會爲您執行它的情況。而當它出現問題的錯誤消息是不準確的:代表/ 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
@MisterMetaphor:correct:http://stackoverflow.com/questions/3392000/interop-between-f-and-c-sharp-lambdas – Mau