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

问题描述

我想坚持使用record,并且不想回到object.所以我想知道是否可以将record private做成field吗?或使private memberrecord.像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.

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

08-27 23:54