问题描述
我想坚持使用record
,并且不想回到object
.所以我想知道是否可以将record private
做成field
吗?或使private member
为record
.像discriminated union
这样的其他concrete types
呢?
I want to stick with record
, and don't want to go back to object
. So I am wondering if it is possible to make a field
of a record private
? or to make a private member
of record
. what about other concrete types
such as discriminated union
?
或者,此要求是否违反语言规范?
Or, does this requirement violate the language spec?
推荐答案
不是,单个字段不可能是私有的: http://msdn.microsoft.com/zh-cn/library/dd233184
Nope, it's not possible for single fields to be private: http://msdn.microsoft.com/en-us/library/dd233184
但是,您可以将所有字段设为私有,并通过属性公开选定的字段.请注意,您将需要一个Create-function来创建记录的实例,因为它的字段是私有的:
However, you can make all fields private and expose selected fields through properties. Note that you will need a Create-function in order to create an instance of the records, since its' fields are private:
type MyRec =
private
{ a : int
b : int }
member x.A = x.a
member private x.Both = x.a + x.b // Members can be private
static member CreateMyRec(a, b) = { a = a; b = b }
但是,成员可以是私有的,就像上面的MyRec.Both
属性一样.
Members can be private though, as in the case of the MyRec.Both
property above.
以上内容使字段专用于MyRec定义的模块,而不是MyRec专用.请参阅丹尼尔对 F#记录出现奇怪的可访问范围的回答字段被声明为私有.
The above makes the fields private to the module that MyRec is defined in, not private to MyRec. See Daniel's answer to Weird accessibility scopes when F# record's fields are declared private.
这篇关于是否可以将记录的字段设为私有?还是将记录成员设为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!