Property vs Function (specifically .NET)

后端 未结 6 2041
花落未央
花落未央 2021-01-12 11:20

I\'ve read some discussions about this subject, and there\'s something I just don\'t understand.

The most common answer seems to be this: use a ReadOnly Property to

6条回答
  •  一向
    一向 (楼主)
    2021-01-12 11:50

    Reason #1 = Properties can be used in data-binding. Methods cannot.

    Reason #2 = When debugging the watch window will automatically expose the properties/expand the object. Methods do not get automatically watched this way.

    I remember reading someplace that the read property should not change the object state. I think that is a good practice to follow especially considering the reason #2. As soon as you watch an object and expand it in the watch the objects state could be changed thus making debugging more difficult.

    Also if a expensive property is bound by accident it can introduce serious performance problems. (Attributes can "hide" properties from data binding but just making them methods means you don't have to worry about it.)

    Properties are conveniences for window development. They are "used" differently in designers etc.

    (I sometimes just expose some variables. But I name them as I would a property. So instead of

    Integer mCounter = 0;

    I just do

    Integer Counter = 0;.

    If I have to do "extra stuff" at some point in the future I create the Property with the same name and rename the variable to mCounter. Admittedly this is laziness on my part and I don't really recomend it. Just wrap it up in a property.)

提交回复
热议问题