Properties vs Methods

后端 未结 16 1888
傲寒
傲寒 2020-11-22 08:23

Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?

We are busy having this debate and have found some areas where it

16条回答
  •  温柔的废话
    2020-11-22 08:28

    As a matter of design Properties represent Data or Attributes of class object, While methods are actions or behaviors of class object.

    In .Net, world there are other implications of using Properties:

    • Properties are used in Databinding, while get_ / set_ methods are not.
    • XML serialization user properties as natural mechanism of serilization.
    • Properties are accessed by PropertyGrid control and intern ICustomTypeDescriptor, which can be used effectively if you are writing a custom library.
    • Properties are controlled by Attributes, one can use it wisely to design Aspect Oriented softwares.

    Misconceptions (IMHO) about Properties' usage:

    • Used to expose small calculations: ControlDesigner.SelectionRules's get block runs into 72 lines!!
    • Used to expose internal Data structures: Even if a property does not map to an internal data member, one can use it as property, if its an attribute of your class. Viceversa, even if its an attribute of your class properties are not advisable, to return array like data members (instead methods are used to return deep copy of members.)

    In the example here it could have been written, with more business meaning as:

    public String Title
    {
        set { Label.Text = text; }
    }
    

提交回复
热议问题