在F#中实现委托接口

时间:2014-09-16 20:09:10

标签: events f#

我想在F#

中实现以下C#接口
interface IDoSomething
{  
   void Process(foo input); 
   event Action<bar> Result; 
} 

但是我在活动/代表部分失败了:

type doSomething() =
    let result = new Event<System.Action<bar>>()    
    interface IDoSomeThing with
        [<CLIEvent>]
        member x.Result = result.Publish 
          // This expression was expected to have type
          // Handler<System.Action<foobar>>    
          //  but here has type
          // System.Action<foobar>  

知道如何做到这一点?

解决方案

type doSomething() =
    let e =  DelegateEvent<_>()  
    let result s = e.Trigger ([| box s |]) 

    let calc input = 
        input 
        |> (...) // The real processing happens here 
        |> result

    interface IDoSomething with
        member x.Process input = calc input
        [<CLIEvent>]
        member x.Result = e.Publish

1 个答案:

答案 0 :(得分:3)

由于您的界面定义了非标准的事件类型,因此您必须使用DelegateEvent<_>而不是(更常见的)Event<_,_>

type DoSomething() =
    let result = DelegateEvent<_>()
    interface IDoSomething with
        member x.Process(input: Foo) = ()
        [<CLIEvent>]
        member x.Result = result.Publish