本文概述
- F#公共访问控制示例
- F#专用访问控制示例
- F#内部访问控制
F#中有3种访问控制类型:
- 公开或默认
- 私人的
- 内部
type AccessControl() =
member public x.a = 10
member public x.display() =
printfn "This is public method"let ac = new AccessControl()
ac.display()
printfn "a = %d" ac.a
输出:
This is public method
a = 10
F#专用访问控制示例专用访问控制受到最大限制, 并且范围有限。 F#提供了private关键字来声明类或类型中的私有成员。私有的范围仅限于在其中声明它的本地块。
type AccessControl() =
member private x.a = 10
member private x.display() =
printf "This is private method"let ac = new AccessControl()
ac.display()// display method is private so can't be accessable ouside the type
printf "a= %d" ac.a// variable is private.
输出:
error FS0491: The member or object constructor 'display' is not accessible.
Private members may only be accessed from within the declaring type.
F#内部访问控制内部访问控制只能从同一程序集访问。程序集是在编译F#代码后由编译器自动生成的文件。它可以是动态链接库(DLL)或可执行文件(exe)。
type AccessControlIN() =
member internal x.a = 10
member internal x.display() =
printfn "This is internal method"let aci = new AccessControlIN()
aci.display()
printfn "a= %d" aci.a
【F#访问控制】输出:
This is internal method
a= 10