Properties vs Methods

后端 未结 16 2028
傲寒
傲寒 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:52

    Properties are really nice because they are accessible in the visual designer of visual studio, provided they have access.

    They use be used were you are merely setting and getting and perhaps some validation that does not access a significant amount of code. Be careful because creating complex objects during validation is not simple.

    Anything else methods are the preferred way.

    It's not just about semantics. Using properties inappropriate start having weirdness occur in the visual studio visual designer.

    For instance I was getting a configuration value within a property of a class. The configuration class actually opens a file and runs an sql query to get the value of that configuration. This caused problems in my application where the configuration file would get opened and locked by visual studio itself rather than my application because was not only reading but writing the configuration value (via the setter method). To fix this I just had to change it to a method.

提交回复
热议问题