How do I create a class instance and fill properties in F#?
In C#, I can:
var n = new Person()
{
FirstNa开发者_StackOverflow中文版me = "John",
LastName = "Smith"
};
Can I do the same in F#? I mean, to create a class and specify some properties.
Yes:
let n = Person(FirstName = "John", LastName = "Smith")
Note that the F# approach is actually much more flexible than the C# approach, in that you can use "post hoc" property assignments with any method call (not just constructors). For example, if the Person
type has a static method called CreatePerson : string -> Person
which creates a new person and assigns the first name, you could also use it like:
let n = Person.CreatePerson("John", LastName = "Smith")
F# also has records which are basically classes with automatically exposed properties that are meant to represent simple aggregates of named values, optionally with members.
type Person = {
FirstName : string;
LastName : string;
}
let p = {FirstName = "John"; LastName = "Smith"}
type Person() =
[<DefaultValue>]
val mutable firstName : string
[<DefaultValue>]
val mutable lastName : string
member x.FirstName
with get() = x.firstName
and set(v) = x.firstName <- v
member x.LastName
with get() = x.lastName
and set(v) = x.lastName <- v
let p = new Person(FirstName = "Nyi", LastName = "Than")
精彩评论