在所有者类中使用属​​性与支持字段 [英] Use of properties vs backing-field inside owner class

查看:18
本文介绍了在所有者类中使用属​​性与支持字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在 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 没有副作用.但是如果稍后我需要在 get 或 set 中添加一些额外的处理怎么办?

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 的内部引用都将在访问该属性时调用这些副作用.现在必须重构所有对 once 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 Lippert 有一篇出色的博客文章回答了这个问题:

如果促使从自动实施更改要显式实现的属性属性是改变语义的财产,那么你应该评估是否需要语义从访问该属性时类内相同于或不同于所需的语义从访问该属性时课外.

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.

如果调查的结果是从班级内部,想要的访问此属性的语义与想要的不同访问属性的语义从外面",那么你的编辑有引入了一个错误.你应该修复漏洞.如果它们相同,那么您的编辑没有引入错误;保持实现相同.

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.

这篇关于在所有者类中使用属​​性与支持字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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