你如何在F#中实现一个接口

时间:2016-01-11 10:22:52

标签: f#

我在C#中有一个接口,如下所示:

public interface IMessageOptions
{
    int ReceiveTimeout { get; set; }
    int PeekTimeout { get; set; }
    bool Transactional { get; set; }
}

我试图在F#中实现它:

type Settings() =
    interface IMessageOptions with
        member this.PeekTimeout: int with get, set
        member this.ReceiveTimeout: int with get, set // error at start of this line
        member this.Transactional: bool with get, set

但是在第一个属性之后我得到了一个错误:

  

“模式中此点或之前的不完整结构化构造”

应该怎么写?

此上下文中是否不允许使用自动属性?

2 个答案:

答案 0 :(得分:6)

以下是其语法:

type Settings() =
   interface IMessageOptions with
      member val PeekTimeout = 0 with get, set
      member val ReceiveTimeout = 0 with get, set
      member val Transactional = false with get, set

区别在于:

  • 使用val代替this.
  • 明确定义默认值
  • 您不必指定类型(尽管可以)

作为参考,以下是如何在F#中定义界面本身:

type IMessageOptions =
  abstract member PeekTimeout : int with get, set
  abstract member ReceiveTimeout : int with get, set
  abstract member Transactional : bool with get, set

答案 1 :(得分:2)

如果您想要自动实施属性,请this is the syntax

type Settings() =
    interface IMessageOptions with
        member val PeekTimeout : int = 0 with get, set
        member val ReceiveTimeout : int = 0 with get, set
        member val Transactional : bool = false with get, set

请注意,您必须明确定义默认值。