在正常情況下,可以通過調用new DelegateType
並將該函數作爲參數傳遞,將F#函數轉換爲代表。但是當代表包含byref
參數時,這是不可能的。例如代碼:爲什麼不能將帶有byref的函數直接轉換爲委託?
type ActionByRef<'a> = delegate of 'a byref -> unit
let f (x:double byref) =
x <- 6.0
let x = ref 42.0
let d = new ActionByRef<_>(f)
將無法編譯,給了以下錯誤:
This function value is being used to construct a delegate type whose signature includes a byref argument. You must use an explicit lambda expression taking 1 arguments.
繼錯誤,修改代碼以使用
let d = new ActionByRef<_>(fun x -> f(&x))
作品。但我的問題是:爲什麼這是必要的?爲什麼F#不允許從命名函數到這個代理的轉換,但是lambda轉換很好?
我在研究another question時遇到了這種行爲。我知道byref
僅用於與其他.Net語言兼容。
有趣的是,我沒有想到這一點。一個挑逗,我認爲'byref'更像'ref',而不是'out'。 – svick 2012-01-31 11:45:05
@svick - 你是對的 - 實際上,在IL級別,標誌是'ref',並且C#'out'根本不存在... – 2012-01-31 13:00:41
Right,C#的'out'實際上是'ref'加上'System.Runtime.InteropServices.Out'屬性。 – ildjarn 2012-01-31 20:23:57