F# 中没有装箱的多参数事件类型

Multiple parameter event type without boxing in F#

我想声明的 C# 等价物很简单:

public event Action<DateTime, int> example;

我希望按如下方式从 C# 订阅此事件:

example += DoSomething;

private static void DoSomething(DateTime time, int count)
{
    Console.WriteLine("Time: {0} Count:{1}", time, count);
}

我可以使用 DelegateEventsee this question), but my understanding is that DelegateEvent.Trigger 将导致值的装箱,因为它们作为对象数组传入。

如何在 F# 中定义多个参数的事件而不装箱

[<Struct>]
type MyEventArgs(date:DateTime,number:int) =
    member x.Date = date
    member x.Number = number

type MyClass() =
    let e = new Event<_>()
    [<CLIEvent>]
    member x.OnEvent = e.Publish
    member private this.FireEvent (s:DateTime) (i:int) = 
        e.Trigger (MyEventArgs(s,i))

然后从 C#:

namespace Test
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      MyClass c = new MyClass ();
      c.OnEvent += (object sender, MyLib.EventArgs a) =>   
        Console.WriteLine("Hello from F#");
    }
  }
}

DelegateEvent 的具体实现确实将参数装入 obj[],但您可以创建自己的 IDelegateEvent 类型:

type T() =
    let handlers = ResizeArray<System.Action<System.DateTime,bool>>()
    let event = { new IDelegateEvent<_> with
                        member __.AddHandler(h) = handlers.Add h 
                        member __.RemoveHandler(h) = handlers.Remove h |> ignore }
    [<CLIEvent>]
    member x.example = event
    member x.Trigger(dt,i) =
        for handler in handlers do
            handler.Invoke(dt,i)

如果这是你经常做的事情,那么你可以将逻辑封装到它自己的 CustomEvent 类型中,而不是通过包含事件的类型传播它。