gpt4 book ai didi

c# - 在所有者类中使用属​​性与支持字段

转载 作者:太空狗 更新时间:2023-10-29 17:48:54 26 4
gpt4 key购买 nike

我喜欢 C# 中的自动实现属性,但最近我的隔间里出现了这头大象,我不知道该如何处理它。

如果我使用自动实现的属性(以下简称“aip”),那么我将不再有内部使用的私有(private)支持字段。这很好,因为 aip 没有副作用。但是,如果稍后我需要在 get 或 set 中添加一些额外的处理怎么办?

现在我需要创建一个支持字段,以便扩展我的 getter 和 setter。这对于使用该类的外部代码来说很好,因为它们不会注意到差异。但是现在所有对 aip 的内部引用都将在访问该属性时调用这些副作用。现在必须重构所有对 once aip 的内部访问以使用支持字段。

所以我的问题是,你们大多数人都做什么?您是使用自动实现的属性还是更喜欢始终使用支持字段?您如何看待具有副作用的属性?

最佳答案

Eric Lippert has an excellent blog post回答了这个问题:

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.

关于c# - 在所有者类中使用属​​性与支持字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2457010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com