From 6665adb75ba5e936ededf22d3a58bf460ed15093 Mon Sep 17 00:00:00 2001 From: Sanchime Date: Sun, 20 Feb 2022 21:33:07 +0800 Subject: [PATCH] =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E5=9F=BA=E6=9C=AC=E7=BB=83=E4=B9=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Basic-practice-of-FSharp.fsproj | 1 + Basic-practice-of-FSharp/TypeCreating.fs | 87 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 Basic-practice-of-FSharp/TypeCreating.fs diff --git a/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj b/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj index 576155b..6dbedd5 100644 --- a/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj +++ b/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj @@ -14,5 +14,6 @@ + \ No newline at end of file diff --git a/Basic-practice-of-FSharp/TypeCreating.fs b/Basic-practice-of-FSharp/TypeCreating.fs new file mode 100644 index 0000000..88c428a --- /dev/null +++ b/Basic-practice-of-FSharp/TypeCreating.fs @@ -0,0 +1,87 @@ +module TypeCreating + +// 可区分联合 +type List = + | Cons of int * List + | Nil + +let list = Cons(1, Cons(2, Cons(3, Nil))) + +printfn "%A" list + +// 记录类型 +type UserInfo = { + Username: string + Password: string +} + +let user = { Username = "小明"; Password = "123456" } + +printfn "%A" user + +// 结构类型 +// val表示字段是公有的 +// member 定义属性或者方法 +type UserInfoBtStruct = struct + val Username: string + val Password: string + new(username: string, password: string) = { Username = username; Password = password } + + member this.Display() = + printfn $"用户名: {this.Username} 密码: {this.Password}" + + member this.ToString() = this.Display() + end + +// 类 +// 类后面的括号表示主构造函数的参数 +// 如果let绑定的是函数,那他将编译为成员方法 +// 如果绑定的是未在任何函数或成员中使用的值,那他将编译为主构造函数中的本地变量 +// do绑定将会被编译为主构造函数 +// 不管使用了哪个构造函数,F#始终会执行let和do绑定 +type UserInfoByClass(username: string, password: string) = + let _username = username + let _password = password + do printfn "%A" "DoBinding" + member this.Username = _username + member this.Password = _password + + member this.Display() = + printfn $"用户名: {this.Username} 密码: {this.Password}" + + member this.ToString() = this.Display() + +// 接口 +// 接口定义与类相似,但是并不实现任何成员,并且所有成员都是抽象的abstract +// 接口默认访问修饰符为public +type IUserInfo = + abstract member Display: unit -> unit + +// 继承接口 +// 使用as关键字可以自定义自我标识符,否则默认为this +type UserInfoWith() = + interface IUserInfo with + member this.Display() = printfn "实现IUserInfo接口的Display方法" + +// 类的继承 +// type class-name(...) +// inherit base-class-name(...) +// other-member... + +// 虚方法与重写 +type BaseClass() = + let mutable counter = 0 + // 虚方法声明 + abstract member Method: int -> int + // 虚方法的默认实现 + default this.Method(a) = counter <- counter + a; counter + +type SubClass() = + inherit BaseClass() + // 重写父类虚方法 + override this.Method(a) = a + 1 + +// 抽象类 +// 抽象类需要在类的前面加个[]特性 +// [] +// type AbstactClass(...) = ... \ No newline at end of file