简体   繁体   English

如何在C#中定义F#中的事件

[英]How do define an event in F# visible from C#

Looking at various bits of documentation, the way of defining an event in F# is to do something like 看看各种文档,在F#中定义事件的方法就是做类似的事情

type xyz () =
    let e = new Event<T>
    member x.something_happened : IEvent<T> = x.Publish

Unfortunately, the type of IEvent is really Miscrosoft.FSharp.Control.IEvent<_>, and it is hence difficult to use from within C#. 不幸的是,IEvent的类型实际上是Miscrosoft.FSharp.Control.IEvent <_>,因此很难在C#中使用。 Some articles suggest adding the CLIEvent attribute to member something_happended above but it seems to make no difference as far as its usability from C# without including the F# library goes. 有些文章建议将CLIEvent属性添加到上面的成员something_happended中,但就C#的可用性而言,它似乎没有任何区别,而不包括F#库。

How do I correctly define an event in F# so I can then add a delegate to it in C# code? 如何在F#中正确定义事件,以便我可以在C#代码中添加一个委托? Many thanks. 非常感谢。

There are two event types in F#, Event<'T> and Event<'Delegate, 'Args> . F#, Event<'T>Event<'Delegate, 'Args>有两种事件类型。 Only the second one is compiled to a .NET event when [<CLIEvent>] is present. [<CLIEvent>]存在时,只有第二个编译为.NET事件。 Here's a working example: 这是一个有效的例子:

type T() =
    let e = Event<EventHandler<_>,_>()

    [<CLIEvent>]
    member x.MyEvent = e.Publish

    member x.RaiseMyEvent() = e.Trigger(x, EventArgs.Empty)

In some cases the compiler generates a warning if [<CLIEvent>] is used with a non-standard event type. 在某些情况下,如果[<CLIEvent>]与非标准事件类型一起使用,编译器将生成警告。 I'm not sure why it doesn't raise a warning for your code (perhaps a bug?). 我不确定为什么它不会对你的代码发出警告(也许是一个错误?)。

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

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