其实对类来说,就只有两种成员,一种是成员变量,另一种就是成员行为,或者说是成员函数了。这是我最初学c++的时候学到的。后来在学java的时候,就发现成员又多了好多种,不过其实那时候还是不是很理解。为什么要分那么多种类干什么呢?不都是一样的吗?
最近在学c#的时候又重新思考了一下这个问题,才发现其中的奥秘啊。其实也不能说是奥秘了,只不过对那么分类有了新的理解。下面就来说说我的理解吧。
C#中成员变量有这么几种:Constants,Fields,Properties,Events,Indexers。其中我觉得有必要探讨一下的是Fields和Properties。因为Constants光看名字就已经很明显了,常量,有些类中有常量,这是一种特殊的Fields,用来服务类的Properties。Events和Indexers看起来则像是一个特殊的Properties。一个类的最重要的是什么东西呢?我这里简单的下个结论吧,我觉得是成员变量!为什么这么说呢?因为类的行为都是通过类的成员变量来体现的,也是根据类的成员变量产生的。比如说一个银行账号Account,很显然它要有一个money的成员变量,这也就是这个类(账号)的核心了。然后,我们根据这个成员变量有了存款deposit和取款withdraw行为(函数)。所以说,成员变量是核心。当然了,有很多是例外的,上面的结论是基于很多条件下产生的。比如说一个utility class的话,可能根本就没有成员变量。
一个类中的成员变量也还是有好多种的,至少要分两种。一种是所谓的核心变量,也就是一个类为什么存在的理由,就像是Account的money一样;另一种是所谓的类变量,相当于局部变量,说成类的全局变量好像更合适,比如说那个Account是否被停掉了呢?如果那些人犯罪了的话就要马上停掉他的账号,防止他继续对账号操作,这个时候我们也许需要一个类变量bool bAvailable用以判断该账户是否还可用。这样看起来,对client用户比较重要的应该是核心类了。当我们review别人写的类的话,主要关注property就好了。我不知道c#为什么分出一个property来,也许有这种可能性。呵呵。看你的代码,别让我受伤。。。
附c#中的Members,according to spec 1.2
Members:
Member | Description |
Constants | The constant values associated with the class |
Fields | The variables of the class |
Methods | The computations and actions that can be performed by the class |
Properties | The actions associated with reading and writing named properties of the class |
Indexers | The actions associated with indexing instances of the class like an array |
Events | The notifications that can be generated by the class |
Operators | The conversions and expression operators supported by the class |
Constructors | The actions required to initialize instances of the class or the class itself |
Destructors | The actions to perform before instances of the class are permanently discarded |
Types | The nested types declared by the class |