简体   繁体   English

F#中的事件和代表

[英]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#. 我没有F#的经验,但在C#中有几行测试代码用于我需要在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. 因为F#不会自动将lambda函数转换为委托 - 但是有一个带有函数的Add方法。 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. 因为F#允许您使用.NET成员作为一等函数。

尝试这个 -

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? 任何人都可以确认它是正确的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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