F#构造函数

F#构造函数 首页 / F#入门教程 / F#构造函数

在F#中,构造函数与其他.Net语言略有不同。总有一个主构造函数可能有参数,也可能没有参数。这些参数的范围遍及整个类。

您可以使用new关键字创建新的附加构造函数。构造函数的主体必须调用类声明顶部指定的主构造函数。

F#构造函数示例

type Employee(name) = 
 class
  do printf "%s" name
 end
let e = new Employee("FSharp")

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/f-sharp-constructor.html

来源:LearnFk无涯教程网

FSharp

F#非参数化构造函数

type Employee(id) = 
 class
  new () =				//This is non parameterized constructor
   printf "This is non parametrized constructor" 
   Employee(12) 
   
 end

let e = new Employee()

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/f-sharp-constructor.html

来源:LearnFk无涯教程网

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()

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/f-sharp-constructor.html

来源:LearnFk无涯教程网

100 Rajkumar 25000.00
101 john 26000.00

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

AI原生应用入门课 -〔李梦冉/程默〕

郭东白的架构课 -〔郭东白〕

Spring编程常见错误50例 -〔傅健〕

高楼的性能工程实战课 -〔高楼〕

爱上跑步 -〔钱亮〕

用户体验设计实战课 -〔相辉〕

MongoDB高手课 -〔唐建法(TJ)〕

Web协议详解与抓包实战 -〔陶辉〕

玩转Git三剑客 -〔苏玲〕

好记忆不如烂笔头。留下您的足迹吧 :)