本文概述
- F#构造函数示例
- F#非参数构造函数
- F#参数化构造函数
你可以使用new关键字创建一个新的附加构造函数。构造函数的主体必须调用在类声明顶部指定的主要构造函数。
F#构造函数示例
type Employee(name) =
class
do printf "%s" name
end
let e = new Employee("FSharp")
输出:
FSharp
F#非参数构造函数
type Employee(id) =
class
new () =// This is non parameterized constructor
printf "This is non parametrized constructor"
Employee(12) endlet e = new Employee()
输出:
This is non parametrized constructor
F#参数化构造函数
type Employee (id, name, salary)=
class
let mutable Id= id
let mutable Name = name
let mutable Salary = salary
member x.Display() =
printfn "%d %s %0.2f" Id Name Salary end
let a = new Employee(100, "Rajkumar", 25000.00)
a.Display()
let a1 = new Employee(101, "john", 26000.00)
a1.Display()
【F#构造函数】输出:
100 Rajkumar 25000.00
101 john 26000.00