在f#中,带强制构造函数参数的对象初始化语法是什么?

本文关键字:对象 初始化 语法 是什么 参数 构造函数 | 更新日期: 2023-09-27 18:13:06

假设有一个类,它有一个公共构造函数,它接受一个形参。此外,我还想设置多个公共属性。f#中的语法是什么?例如在c#

public class SomeClass
{
    public string SomeProperty { get; set; }
    public SomeClass(string s)
    { }
}
//And associated usage.
var sc = new SomeClass("") { SomeProperty = "" };
在f#中,我可以使用构造函数或属性设置器来完成此操作,但不能像在c#中那样同时使用这两种方法。例如,以下

是无效的
let sc1 = new SomeClass("", SomeProperty = "")
let sc2 = new SomeClass(s = "", SomeProperty = "")
let sc3 = new SomeClass("")(SomeProperty = "")

看起来我错过了什么,但是什么?

正如David指出的那样,在f#中完成所有这些工作,但由于某种原因,至少对我来说:),当在f#中使用的类在c#中定义时,它变得困难。关于这方面的一个例子是TopicDescription(为了增加一个例子,为了弥补一些公共的东西)。可以这样写,例如

let t = new TopicDescription("", IsReadOnly = true)

,对应的编译错误将是Method 'set_IsReadOnly' is not accessible from this code location

在f#中,带强制构造函数参数的对象初始化语法是什么?

您的问题是IsReadOnly有一个内部setter。

member IsReadOnly : bool with get, internal set

如果你想直接设置它,你需要子类TopicDescription

您正在查看的构造函数语法完全可以接受。

let test = new Microsoft.ServiceBus.Messaging.TopicDescription("", EnableBatchedOperations=true)

我从来没有用f#编程,但这似乎对我来说很好:

type SomeClass(s : string) =
    let mutable _someProperty = ""
    let mutable _otherProperty = s
    member this.SomeProperty with get() = _someProperty and set(value) = _someProperty <- value
    member this.OtherProperty with get() = _otherProperty and set(value) = _otherProperty <- value
let s = new SomeClass("asdf", SomeProperty = "test");
printf "%s and %s" s.OtherProperty s.SomeProperty;

输出"asdf and test"


另外,下面的代码对我来说很好:

public class SomeClass
{
    public string SomeProperty { get; set; }
    public string OtherProperty { get; set; }
    public SomeClass(string s)
    {
        this.OtherProperty = s;
    }
}

然后在f#:

let s = SomeClass("asdf", SomeProperty = "test")