当F#记录的字段被声明为私有时,奇怪的可访问范围 [英] Weird accessibility scopes when F# record's fields are declared private
问题描述
当F#记录的字段部分被声明为私有时,我只是注意到了一种与之相反的直观行为. (这与
I just noticed a rather counter intuitive behaviour when the field part of an F# record is declared private. (This is related to Is it possible to make a field of a record private? or to make a member of record private?)
在此示例中...
type MyRec =
private // Fields declared private, or at least I thought so.
{ a : int
b : int }
member x.A = x.a
member private x.Both = x.a + x.b
static member CreateMyRec(a, b) = { a = a; b = b }
let foo = MyRec.CreateMyRec(1,2)
let bar = foo.a // No error. Huh?
let baz = foo.Both // Error: not accessible.
...如预期的那样,在类型声明范围之外无法访问私有成员Both
.但是,可以访问字段a
.
...the private member Both
is inaccessible outside the type declaration scope, as is expected. However, the field a
is accessible.
如果将MyRec放在模块中,则该字段将变为该模块的私有字段.这就是您希望模块中的顶层声明表现出来的方式,但是我希望在类型中声明为private的任何内容对于该类型都是私有的,而不是对其封闭模块的私有.
If you put MyRec in a module, the fields become private to that module. That's how you'd expect a top level declaration in the module to behave, but I expected that anything declared private within a type, would be private to that type, not to its enclosing module.
这种行为实际上很奇怪吗,还是我在这里的推理中遗漏了一些东西?
Is this behaviour actually weird, or am I missing something in my reasoning here?
推荐答案
据我所知,这是一个文档不足的功能.但是,该规范的第10.5节可访问性注释 ,状态:
As far as I can tell, this is an under-documented feature. But, section 10.5 of the spec, Accessibility Annotations, states:
在类型,模块或模块中的类型表示形式上的私有表示对模块而言是私有的".
private on a type, module, or type representation in a module means "private to the module."
类型表示"是与记录字段相关的部分.
"type representation" being the part relevant to record fields.
这篇关于当F#记录的字段被声明为私有时,奇怪的可访问范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!