How do define an event in F# visible from C#

耗尽温柔 提交于 2019-12-12 15:57:32

问题


Looking at various bits of documentation, the way of defining an event in F# is to do something like

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#. 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.

How do I correctly define an event in F# so I can then add a delegate to it in C# code? Many thanks.


回答1:


There are two event types in F#, Event<'T> and Event<'Delegate, 'Args>. Only the second one is compiled to a .NET event when [<CLIEvent>] is present. 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. I'm not sure why it doesn't raise a warning for your code (perhaps a bug?).



来源:https://stackoverflow.com/questions/24435299/how-do-define-an-event-in-f-visible-from-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!