In F# how can I produce an expression with a type of Func<obj>?

旧时模样 提交于 2019-12-09 14:25:31

问题


I'm working with an api that requires a value of type Func. (Specifically, I'm trying to call ModelMetadataProviders.Current.GetMetadataForType().

How can I construct that value in F#?


回答1:


When calling a method that takes any delegate of the Func you shouldn't need to explicitly create the delegate, because F# implicitly converts lambda expressions to delegate type (in member calls). I think that just calling the method with lambda function should work (if it doesn't, could you share the error message?)

Here is a simple example that demonstrates this:

type Foo() = 
  member x.Bar(a:System.Func<obj>) = a.Invoke()

let f = Foo()
let rnd = f.Bar(fun () -> new Random() :> obj)

In your case, I suppose something like this should work:

m.GetMetadataForType((fun () -> <expression> :> obj), modelType)

Note that you need explicit upcast (expr :> obj), to make sure the lambda function returns the right type (obj). If you want to assign the lambda function to a local value using let, then it won't work, because implicit conversion works only when it is passed as an argument directly. However, in that case, it makes the code a bit nicer.




回答2:


You can normally pass in any () -> obj and it will be automatically converted to Func<obj>. You may need to wrap your fun with Func<obj>:

> let d : Func<obj> = Func<obj>(fun () -> box "hello");;

val d : Func<obj>



回答3:


let f = new System.Func<obj>(fun() -> printfn "ok"; new obj())


来源:https://stackoverflow.com/questions/3238406/in-f-how-can-i-produce-an-expression-with-a-type-of-funcobj

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!