是否可以将记录的字段设为私有

是否可以将记录的字段设为私有

本文介绍了是否可以将记录的字段设为私有?或将记录成员设为私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想坚持使用record,不想回到object.所以我想知道是否有可能使 record privatefield 成为可能?或者制作recordprivate member.其他具体类型discriminated union怎么样?

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/en-us/library/dd233184

Nope, it's not possible for single fields to be private: http://msdn.microsoft.com/en-us/library/dd233184

但是,您可以将所有字段设为私有并通过属性公开选定的字段.请注意,您将需要一个 Create 函数来创建记录的实例,因为它的字段是私有的:

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 私有.请参阅 Daniel 对 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.

这篇关于是否可以将记录的字段设为私有?或将记录成员设为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 23:54