在F#中创建操作以使用c#方法 [英] Create an action in F# in order to use a c# method
问题描述
我想从HttpListener的Owin实现中使用此方法:
I would like to use this method from Owin implementation of HttpListener :
public static IDisposable Create(AppFunc app, IDictionary<string, object> properties)
AppFunc的签名如下:
AppFunc has a signature like this :
IDictionnary<string,Object> -> Task
我想创建一个任务,但是它需要一个动作,但是我不知道如何在F#中完成它.到目前为止,我管理的最好的方法是使用此问题中的代码:
I wanted to create a task but it requires an action, and I failed to know how to do it in F#. The best I managed so far was using the code in this question :
module CsharpAction
open System
type Wrapper<'T>(f:'T -> unit) =
member x.Invoke(a:'T) = f a
let makeAction (typ:Type) (f:'T -> unit) =
let actionType = typedefof<Action<_>>.MakeGenericType(typ)
let wrapperType = typedefof<Wrapper<_>>.MakeGenericType(typ)
let wrapped = Wrapper<_>(f)
Delegate.CreateDelegate(actionType, wrapped, wrapped.GetType().GetMethod("Invoke"))
program.fs
program.fs
let yymmdd1 (date:DateTime) = date.ToString("yy.MM.dd")
let printSuccess = fun() -> printfn "Success %s" (yymmdd1 DateTime.Now )
let actionTask = CsharpAction.makeAction (typeof<string>) (printSuccess)
let mutable properties = Dictionary(dict [("fooKey", new Object())])
let server = OwinServerFactory.Create((fun (props) -> new Task(actionTask)) , properties)
但随后它告诉我:该表达式应具有类型操作,但此处具有类型委托
我应该从F#中执行对C#代码的操作吗?或者我应该在c#代码上工作以便给f#带来一些好处,例如等待委托而不是采取行动?
Should I give from F# an action to c# code? or should I work on the c# code in order to give f# some niceties , for instance waiting for delegate instead of action ?
我正在调侃我的知识极限,我确实感到了痛苦.可以肯定的是,我将学到很多东西,但是如果您愿意帮助我迈出第一步……
I am flirting with the limits of my knowledge and I do feel the pain. Pretty sure, I will have to learn a lot, but if you would be so kind as to help me climb the first steps...
推荐答案
您无需使用反射即可在F#中创建委托.您可以完全放弃代码的第一部分(您的 CsharpAction
模块).
You don't need to use reflection to create delegates in F#. You can ditch the first part of your code altogether (your CsharpAction
module).
对于第二段代码,请尝试以下操作:
As for the second chunk of code, try this:
open System
open System.Collections.Generic
open System.Threading.Tasks
let yymmdd1 (date : DateTime) = date.ToString "yy.MM.dd"
let printSuccess () = printfn "Success %s" (yymmdd1 DateTime.Now)
let server =
let actionTask = Action printSuccess
let properties = Dictionary (dict ["fooKey", obj ()])
OwinServerFactory.Create((fun props -> new Task (actionTask)), properties)
这篇关于在F#中创建操作以使用c#方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!