📜  F#访问控制

📅  最后修改于: 2021-01-01 14:45:54             🧑  作者: Mango

F#访问控制

访问控制指定代码的可访问性。通过使用这些,您可以指定数据,方法,类等的范围。

F#中有3种访问控制类型:

  • 公开或默认
  • 私人的
  • 内部

F#公共访问控制示例

公共访问控制也称为默认。所有人都可以使用。如果您未在代码中明确指定任何访问控制,则默认情况下,它将遵循公共访问控制。

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

输出:

This is internal method
a= 10