简体   繁体   中英

Events and Delegates in F#

I don't have any experience in F# but have a few lines of test code in C# for a framework I've made that I need to rewrite in F#.

Any help would be appreciated.

    bar.Ready += new Agent.ReadyHandler(bar_Ready);               

    static void bar_Ready(string msg)
    {    
       Console.WriteLine(msg.body);  
    }

Just to clarify - the shorter version should correctly be:

bar.Ready.Add(fun msg -> System.Console.WriteLine(msg))  

Because F# doesn't automatically convert lambda functions to delegates - but there is an Add method that takes a function. This can then be written even simpler like this:

bar.Ready.Add(System.Console.WriteLine)  

Because F# allows you to use .NET members as first-class functions.

尝试这个 -

bar.Ready.AddHandler(new Agent.ReadyHandler (fun sender msg -> System.Console.WriteLine(msg)))

I have played a lot with this and this is the code that work.

bar.add_Ready(fun msg -> Console.WriteLine(msg))

I don't know how theoreticly correct it is but it works fine.

Can any one confirm it is correct?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM