自定义类型基本练习
This commit is contained in:
parent
2e9d5613c5
commit
6665adb75b
|
@ -14,5 +14,6 @@
|
|||
<Compile Include="FunctionSign.fs" />
|
||||
<Compile Include="CurryingFunction.fs" />
|
||||
<Compile Include="Loop.fs" />
|
||||
<Compile Include="TypeCreating.fs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
|
@ -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
|
||||
|
||||
// 抽象类
|
||||
// 抽象类需要在类的前面加个[<AbstactClass>]特性
|
||||
// [<AbstactClass>]
|
||||
// type AbstactClass(...) = ...
|
Loading…
Reference in New Issue