如何在C#中可见的F#中定义事件 [英] How do define an event in F# visible from C#
问题描述
查看文档的各个方面,在F#中定义事件的方法是执行类似
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
不幸的是,IEvent的类型实际上是Miscrosoft.FSharp.Control.IEvent< __,因此很难在C#中使用.一些文章建议将CLIEvent属性添加到上面的something_happended成员,但是就其在C#中的可用性(不包括F#库)而言,似乎没有什么区别.
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.
如何正确定义F#中的事件,以便随后可以使用C#代码向其添加委托?非常感谢.
How do I correctly define an event in F# so I can then add a delegate to it in C# code? Many thanks.
推荐答案
F#中有两种事件类型, Event<'T>
和 Event<'Delegate, 'Args>
.存在[<CLIEvent>]
时,仅第二个事件被编译为.NET事件.这是一个工作示例:
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)
在某些情况下,如果[<CLIEvent>]
与非标准事件类型一起使用,则编译器会生成警告.我不确定为什么它不会对您的代码发出警告(也许是错误?).
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?).
这篇关于如何在C#中可见的F#中定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!