In F #, what is the syntax of an object initializer with a required constructor parameter?

Let's say there is a class that has one open constructor that takes one parameter. In addition, there are several public properties that I would like to set. What will be the syntax for F #? For example, 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 do this using the property constructor or, but not both at the same time, as in C #. For example, the following are not valid

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

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

<edit: As David pointed out, all this works in F #, but for some reason, at least for me :), it becomes difficult when the class to be used in F # is defined in C #. For example, with the example TopicDescription (to make something public enough, as for the added example). You can write, for example,

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

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

+6
source share
2 answers

The problem you are facing is that IsReadOnly has an internal setter.

 member IsReadOnly : bool with get, internal set 

If you want to install it directly, you will need a subclass of TopicDescription .

The syntax of the constructor you are looking at is perfectly acceptable.

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

compiles fine for me.

+6
source

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; 

This displays "asdf and test" .


Also, 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") 
+6
source

Source: https://habr.com/ru/post/972250/


All Articles