为什么...
type IntDelegate = delegate of int -> unit type ListHelper = static member ApplyDelegate (l : int list) (d : IntDelegate) = l |> List.iter (fun x -> d.Invoke x) ListHelper.ApplyDelegate [1..10] (fun x -> printfn "%d" x)不能编译,当时:
type IntDelegate = delegate of int -> unit type ListHelper = static member ApplyDelegate (l : int list, d : IntDelegate) = l |> List.iter (fun x -> d.Invoke x) ListHelper.ApplyDelegate ([1..10], (fun x -> printfn "%d" x))是吗?
唯一的区别是第二个 ApplyDelegate 将其参数作为元组。
The only difference that is that in the second one, ApplyDelegate takes its parameters as a tuple.
此函数需要太多的参数,或者在一个不需要函数的上下文中使用
This function takes too many arguments, or is used in a context where a function is not expected
推荐答案
没有看到规范确认,但我猜测从lambda到命名委托类型的隐式转换只发生在成员调用中。
I haven't looked at the spec to confirm, but I am guessing that the implicit conversion from "lambda" to "named delegate type" only occurs in a "member invocations".
您可以随时使转换显式:
You can always make the conversion explicit:
ListHelper.ApplyDelegate [1..10] (IntDelegate(fun x -> printfn "%d" x))(错误诊断相当差;我将文件一个错误。)
(The error diagnostic is quite poor; I'll file a bug.)
编辑:
对于赢家...
是的, spec 说
8.13.6成员调用中的类型导向转换如中所述方法应用程序解析(参见§14.4)中,两个类型导向转换在方法调用中应用。
8.13.6 Type-directed Conversions at member invocations As described in Method Application Resolution (see §14.4), two type-directed conversions are applied at method invocations.
如果一个正式参数是委托,则键入DelegateType,实际的参数在语法上是函数 value(fun ...),那么参数是解释,就好像已经写了 new DelegateType(fun ...)。
If a formal parameter is of delegate type DelegateType, and an actual argument is syntactically a function value (fun ...), then the parameter is interpreted as if it had been written new DelegateType(fun ...).
lambdas自动转换为仅在成员调用中委派类型。在curried成员的情况下,传递的第一个参数是成员调用,然后返回一个函数值来应用第二个参数,函数调用不具有这个隐式转换规则。
that lambdas get converted automagically to delegate types only at "member invocations". In the case of the curried member, the first argument passed is a member invocation, but then that returns a function value to apply the second argument, and function invocations do not have this implicit conversion rule.
更多推荐
在F#中用Lambda表达式创建代表
发布评论