当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《你如何在F#中实现一个接口》经验,为你挑选了2个好方法。

我在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

但是在第一个属性说:

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

怎么写呢?

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



1> Mikhail Shil..:

这是以下语法:

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



2> Mark Seemann..:

如果要自动实现的属性,则语法如下:

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

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

推荐阅读
手机用户2402851335
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有