【问题标题】:Having issues understanding class constructors in F#在 F# 中理解类构造函数时遇到问题
【发布时间】:2019-11-04 05:36:21
【问题描述】:

我有以下代码:

模块 ExchangeSocket =

type Socket(url, id, key) =

    let Communicator = new TestCommunicator(url)
    let Client = new WebsocketClient(Communicator)

    do
        Communicator.Name <- "test"
        Communicator.ReconnectTimeoutMs <- int (TimeSpan.FromSeconds(30.).TotalMilliseconds)

如果我们看最后两行,C#的用法是这样的:

Communicator = new WebsocketCommunicator(wsUrl) { Name = "tst", ReconnectTimeoutMs = (int) TimeSpan.FromSeconds(30).TotalMilliseconds };

现在我读到要创建一个类构造函数,我必须使用'new'关键字;所以我让字段成员并做一个“新”部分:

    member this.communicator : TestCommunicator
    member this.client : WebsocketClient

    new() =
        this.communicator <- new TestCommunicator(url)
        this.client <- new WebsocketClient(this.communicator)

但这不起作用(在本例中第 15 行是顶行)

Socket.fs(15, 64): [FS0010] 成员定义中在此点或之前的不完整结构化构造。应为“with”、“=”或其他标记。

我的问题是:

  • 如何进行这项工作?
  • “新”带来了什么“做”没有?

【问题讨论】:

    标签: c# f#


    【解决方案1】:

    现在我读到要创建一个类构造函数,我必须使用 'new' 关键字

    要制作其他类构造函数,您应该使用new 关键字。这里的主构造函数就足够了。

    member this.communicator : TestCommunicator 中,虽然您已指定属性communicator 的类型,但您尚未指定如何获取(或设置)该属性。如错误消息所述,它缺少 = ...with get/set

    new() =
        this.communicator <- new TestCommunicator(url)
        this.client <- new WebsocketClient(this.communicator)
    

    当你修复上一个错误时,你会在这里得到另一个错误,因为 1.new() 应该返回一个 Socket,并且 2.它引用了不在范围内的 thisurl

    可能你想要的是:

    type Socket(url, id, key) =
        let communicator =
            new TestCommunicator(url,
                Name = "test",
                ReconnectTimeoutMs = int (TimeSpan.FromSeconds(30.).TotalMilliseconds))
        let client = new WebsocketClient(communicator)
        member _.Communicator = communicator
        member _.Client = client
    

    虽然此答案符合您的要求,但最好阅读类规范(请参阅https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/classeshttps://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/members/)以及一些使用示例。您的代码表明您在猜测哪种方法不正确。

    【讨论】:

    • 我现在明白了;我以前浏览过文档,但这有点像用六包而不是塑料把罐子绑在一起:)现在我看得更清楚了。谢谢!当你用 _ 声明一个成员时。和这个一样吗?
    • Thomas,在 F# 中,'self-identifier'(当前实例的名称)可以是任何有效名称,而不仅仅是 C# 中的 'this'。同样在 F# 中,_ 用于表示使用的实际名称无关紧要。所以综合起来,你可以从“__”中推断出来。在类的这个特定实例成员中,根本不使用自标识符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多