所有者类中物业VS后盾场使用 [英] Use of properties vs backing-field inside owner class

查看:84
本文介绍了所有者类中物业VS后盾场使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在C#中自动实现的属性,但最近也一直这头大象站在我的房间,我不知道他怎么做。

I love auto-implemented properties in C# but lately there's been this elephant standing in my cubicle and I don't know what to do with him.

如果我使用自动实现的属性(以下简称AIP),那么我不再有一个私人支持字段在内部使用。这是很好,因为AIP没有任何副作用。但是,如果以后我需要在获取或设置添加一些额外的处理?

If I use auto-implemented properties (hereafter "aip") then I no longer have a private backing field to use internally. This is fine because the aip has no side-effects. But what if later on I need to add some extra processing in the get or set?

现在我需要建立一个后备领域,所以我可以扩大我的getter和setter。这是罚款使用类外部代码,因为他们不会注意到其中的差别。但现在所有的AIP内部参考的打算时,他们访问属性来调用这些副作用。现在到了所有的内部访问一次AIP必须重构使用后备场。

Now I need to create a backing-field so I can expand my getters and setters. This is fine for external code using the class, because they won't notice the difference. But now all of the internal references to the aip are going to invoke these side-effects when they access the property. Now all internal access to the once aip must be refactored to use the backing-field.

所以我的问题是,什么做你做什么?您是否使用自动实现属性或做你喜欢总是使用后备场?你认为什么有副作用的属性呢?

So my question is, what do most of you do? Do you use auto-implemented properties or do you prefer to always use a backing-field? What do you think about properties with side-effects?

推荐答案

Eric利珀特拥有一支优秀的博客文章认为回答这个问题:

如果明确实施了积极性自动执行
属性的
变化的原因
属性被更改属性的语义
,则应该
评估访问来自$属性时访问类内从
中的属性时所需的语义
是否是相同的或
将所需的语义
不同b $ b中的类之外。

If the reason that motivated the change from automatically implemented property to explicitly implemented property was to change the semantics of the property then you should evaluate whether the desired semantics when accessing the property from within the class are identical to or different from the desired semantics when accessing the property from outside the class.

如果该调查的结果是
从类中,访问此属性的所需
语义
是从外部访问属性
的期望
语义不同,那么您的编辑有
引入的错误。您应该修复
错误。如果它们是相同的,那么你的
编辑还没有出台一个bug;继续
执行相同的。

If the result of that investigation is "from within the class, the desired semantics of accessing this property are different from the desired semantics of accessing the property from the outside", then your edit has introduced a bug. You should fix the bug. If they are the same, then your edit has not introduced a bug; keep the implementation the same.

这篇关于所有者类中物业VS后盾场使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆