简体   繁体   中英

How to write an Event member for an F# interface?

I am new to F#. In C#, I have an interface defined as:

public interface IMenuEvents
   {
       event Action SaveEvent;
       event EventHandler<ParagraphReadyEventArgs> ParagraphReadyEvent;

       ....
   }

where

public class ParagraphReadyEventArgs : System.EventArgs
    {
        public ParagraphReadyEventArgs(string paragraph_title)
        {
            ParagraphTitle = paragraph_title;
        }

        public string ParagraphTitle { get; }
    }

How is the interface IMenuEvents written in F# ?

Thank you for any help.

Given declaration translates to

open System

type ParagraphReadyEventArgs(paragraphTitle: string) =
    inherit EventArgs()
    member val ParagraphTitle = paragraphTitle

type IMenuEvents =
    [<CLIEvent>]
    abstract member SaveEvent : IDelegateEvent<EventHandler>

    [<CLIEvent>]
    abstract member ParagraphReadyEvent : IDelegateEvent<EventHandler<ParagraphReadyEventArgs>>

Key difference is that EventHandler wrapped inside IDelegateEvent<T>

Behind the scenes you get same interface that you could get with C#. Decompilation

I don't understand why F# chose to make things that complicated yet. Hope somebody have an answer for this question

Few words about original design: It's recommended for all events to have type EventHandler or EventHandler<TEventArgs> , don't use custom event types. If you concern about memory allocation from EventArgs , then use EventArgs.Empty instead of new EventArgs()

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