简体   繁体   中英

In F#, what is the object initializer syntax with a mandatory constructor parameter?

Let's say there's a class that with one public constructor, which takes one parameter. In addition, there are also multiple public properties I'd like to set. What would be the syntax for that in F#? For instance in C#

public class SomeClass
{
    public string SomeProperty { get; set; }

    public SomeClass(string s)
    { }
}

//And associated usage.
var sc = new SomeClass("") { SomeProperty = "" };

In F# I can get this done using either the constructor or property setters , but not both at the same time as in C#. For example, the following aren't valid

let sc1 = new SomeClass("", SomeProperty = "")
let sc2 = new SomeClass(s = "", SomeProperty = "")
let sc3 = new SomeClass("")(SomeProperty = "")

It looks like I'm missing something, but what?

<edit: As pointed out by David , doing it all in F# works, but for some reason, at least for me :), it gets difficult when the class to be used in F# is defined in C#. As for an example on such is TopicDescription (to make up something public enough as for an added example). One can write, for instance

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

and the corresponding compiler error will be Method 'set_IsReadOnly' is not accessible from this code location .

I never program in F#, but this seems to work fine for me:

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;

That outputs "asdf and test" .


Additionally, the following code works fine for me:

public class SomeClass
{
    public string SomeProperty { get; set; }
    public string OtherProperty { get; set; }

    public SomeClass(string s)
    {
        this.OtherProperty = s;
    }
}

Then in F#:

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

The problem you're having is that IsReadOnly has an internal setter.

member IsReadOnly : bool with get, internal set

If you want to set it directly you're going to need to subclass TopicDescription .

The constructor syntax you're looking at is perfectly acceptable.

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

compiles just fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM