我认为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
Run Code Online (Sandbox Code Playgroud)
最后一行无法编译,错误是:
This expression was expected to have type
System.Func<obj,obj>
but here has type
'a -> obj
Run Code Online (Sandbox Code Playgroud)
显然,该功能f没有签名'a > obj.如果F#3.1编译器对第一个字典赋值感到满意,那为什么不是第二个呢?
我正在使用Microsoft.FSharp.Reflection.FSharpValue.MakeUnion,这需要一个Reflection.UnionCaseInfo和一个obj[](可以是空的)作为参数.
但是,我正在
Type mismatch. Expecting a obj [] but given a string [] The type 'obj' does not match the type 'string'使用函数的结果调用string[].
我可以创建这个事件的最简单的例子如下(我有一个测试包围这个,它不会编译因为标记的行!!.
let one (a:obj[]) = a |> Array.map (fun o->printfn "%A" o) |> ignore
one [|"a";"b";"c"|] // OK!
let str = [|"a";"b";"c"|] //the equivalent of my function return
one str//!!Type mismatch.
Run Code Online (Sandbox Code Playgroud)
我不确定我是不是要将字符串[]转换/转换为obj []或者......好吧,如果我正在做其他错误的事我不知道.
编辑:实际问题如下所述
let split (by:string) (input:string) = System.Text.RegularExpressions.Regex.Split(input,by)
let buildArgs content =
match content with …Run Code Online (Sandbox Code Playgroud)