在F#中,如何生成具有Func< obj>类型的表达式? [英] In F# how can I produce an expression with a type of Func<obj>?
问题描述
我正在使用需要Func类型值的api。 (具体来说,我正在尝试调用 ModelMetadataProviders.Current.GetMetadataForType()。
I'm working with an api that requires a value of type Func. (Specifically, I'm trying to call ModelMetadataProviders.Current.GetMetadataForType().
如何在F#中构造该值?
How can I construct that value in F#?
推荐答案
在调用接受 Func
的任何委托的方法时,您不需要显式创建委托,因为F#会将lambda表达式隐式转换为委托类型(在成员调用中)我认为仅使用lambda函数调用该方法应该可以工作(如果不可行,您是否可以共享错误消息?)
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)
请注意,您需要显式上传( expr:> ; obj
),以确保lambda函数返回正确的类型( obj
)。如果要使用 let
将lambda函数分配给局部值,则它将不起作用,因为隐式转换仅在直接将其作为参数传递时才有效。但是,在那种情况下,它会使代码变得更好一些。
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.
这篇关于在F#中,如何生成具有Func< obj>类型的表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!