[英]Having issues understanding class constructors in F#
我有以下代码:
模块 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 };
现在我读到要创建一个 class 构造函数,我必须使用“新”关键字; 所以我让字段成员并做一个“新”部分:
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”、“=”或其他标记。
我的问题是:
现在我读到要创建一个 class 构造函数,我必须使用“新”关键字
要制作额外的 class 构造函数,您应该使用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. 它引用this
和url
,它们不在 scope 中。
可能你想要的是:
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/classes和https://docs。 microsoft.com/en-us/dotnet/fsharp/language-reference/members/ )和一些使用示例。 您的代码表明您在猜测这不是正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.