📅  最后修改于: 2021-01-01 14:30:01             🧑  作者: Mango
F#是一种功能编程语言。它还支持面向对象的编程方法,并允许我们创建类和对象。
对象是现实世界的实体。可以是什么?手机,汽车,足球等
对象是类的实例。我们可以使用此类的对象来访问该类的所有成员。
让我们看一个如何在F#中创建对象的示例。
let objectName = new ClassName()
在上面的示例中,objectName是引用类的对象的名称。 New是一个关键字,用于为对象分配内存。 ClassName是我们要创建对象的类的名称。
类是一个模板或对象的print。它用于封装数据成员和成员方法。它可以包含字段,方法,构造函数,静态方法等。
此F#类示例仅包含两个字段和一个方法。我们已经通过使用object在此方法中显示了字段值。
type Student (id,name)=
class
member x.show =
printf "%d \n%s" id name
end
let a = new Student (12,"FSharp")
a.show
输出:
12 FSharp
type Student ()=
class
let mutable id = 0
let mutable name = " "
member x.Insert(v1,v2) =
id <- v1
name <-v2
member x.Show = printfn "%d %s" id name
end
let a = new Student()
a.Insert(25,"RajKumar")
a.Show
a.Insert(26,"John")
a.Show
a.Insert(27,"Mariam")
a.Show
输出:
25 RajKumar
26 John
27 Mariam
type Employee ()=
class
let mutable id = 0
let mutable name = " "
let mutable salary = 0.0
member x.Insert(i,n,s) =
id <- i
name <-n
salary<-s
member x.Show =
printfn "%d %s %0.2f" id name salary
end
let a = new Employee()
a.Insert(25,"RajKumar",25000.00)
a.Show
a.Insert(26,"John",26000.00)
a.Show
let a1 = new Employee()
a1.Insert(27,"Mariam",27000.00)
a1.Show
输出:
25 RajKumar 25000.00
26 John 26000.00
27 Mariam 27000.00
type student() = class
member ob.name = "Rajkumar"
member ob.id = 102
end
type studenttest() = class
member ob.display()=
let s = new student()
printfn "%d %s" s.id s.name
end
let s1 = new studenttest()
s1.display()
输出:
102 Rajkumar