在同一单位的类方法中使用属性而不是字段是不好的做法? [英] Using properties instead of fields in class methods of the same unit is a bad practice?
问题描述
我已经为给定的类宣布了一个私有字段和一个公共属性。
从其他单位可以通过提供访问权限的公共属性来访问该字段
但是在同一个单元中声明此类的内容,我可以选择通过属性直接访问该字段或。
建议的最佳做法是什么?直接读/写字段或通过提供读写权限的属性?
与 David的味道相反,我总是使用私人/受保护的字段,但只能在同一个类(私人时)内或派生中(当被保护时)。这个原因对我而言是可读性的:</ p> 这里的关键点是一致。选择一个,并坚持下去。 由于Jerry的评论而更新: 关于一致的观点是对每个人自己的利益的一般建议。使用一个默认语法来自定义你的代码,你的代码在你的余生中将是清晰的(对你而言)。 当然,当您选择使用私有字段时,会出现偶然情况,您必须使用该属性。但是这反过来也适用:如果您选择使用该属性,则会出现必须使用私有字段的情况。我只是说,当你坚持使用系统时,例外情况将会更清楚地看起来像是例外。 I have declared a private field and a public property for a given class. From other units I can access the field through the public property that provides access to it. But inside the same unit where this class is declared I have the choice to access the field directly or through the property. What is the suggested best practice: direct read/write to the field or through the property that provides read and write access to it? Contrary to David's taste, I always use the private/protected field, but only within the same class (when private) or within a derivative (when protected). Strangly enough, the reason is readability for me too: The key point here is being consistent. Choose one, and stick to it. There is no right nor wrong. Update due to Jerry's comment: My point about being consistent is a general advise for everyone's own benefit. Accustom yourself with one default syntax, and your code will be crystal clear (to you I mean) for the rest of your life. Of course, when you choose using private fields, there will be incidental situations you must use the property instead. But this applies vice versa: if you choose to use the property, then there will be situations you have to use the private field. I am only saying that when you stick to a system, the exceptions will more clearly look like exceptions. 这篇关于在同一单位的类方法中使用属性而不是字段是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!