Weird accessibility scopes when F# record's fields are declared private

自闭症网瘾萝莉.ら 提交于 2019-12-07 00:28:31

问题


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?)

In this example...

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.

...the private member Both is inaccessible outside the type declaration scope, as is expected. However, the field a is accessible.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/14461734/weird-accessibility-scopes-when-f-records-fields-are-declared-private

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!