Exposing Member Objects As Properties or Methods in .NET

后端 未结 7 2100
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 05:58

In .NET, if a class contains a member that is a class object, should that member be exposed as a property or with a method?

7条回答
  •  广开言路
    2020-12-05 06:07

    Overview

    Generally, properties store data for an object, such as Name, and methods are actions an object can be asked to perform, such as Move or Show. Sometimes it is not obvious which class members should be properties and which should be methods - the Item method of a collection class (VB) stores and retrieves data and can be implemented as an indexed property. On the other hand, it would also be reasonable to implement Item as a method.

    Syntax

    How a class member is going to be used could also be a determining factor in whether it should be represented as a property or a method. The syntax for retrieving information from a parameterized property is almost identical to the syntax used for a method implemented as a function. However, the syntax for modifying such a value is slightly different.

    If you implement the member of a class as a property, you must modify it's value this way:

    ThisObject.ThisProperty(Index) = NewValue

    if the class member is implemented as a method, the value being modified must be modified using an arguement:

    ThisObject.ThisProperty(Index, NewValue)

    Errors

    An attempt to assign a value to a read-only property will return a different error message than a similar call to a method. Correctly implemented class members return error messages that are easier to interpret.

提交回复
热议问题