如何避免财产递归 [英] How to avoid property recursion
问题描述
这最近在我正在进行的一个项目中给我带来了打击.大多数人都熟悉财产递归:
This hit me recently on a project I was working on. Most people are familiar with property recursion:
public int Test
{
get { return this.test; }
set { this.Test = value; }
}
private int test;
您不小心将一个大写的T放在了此setter中,并且已经对 StackoverflowException
敞开心yourself.更糟糕的是,如果您没有定义它,Visual Studio经常会自动将外壳改正为无效状态.
You accidentally put an upper-case T in this setter, and you've opened yourself up to a StackoverflowException
. What's worse is if you've not defined it, often visual studio will auto-correct the casing for you to the invalid state.
最近我在构造函数中做了类似的事情:
I did something similar however in a constructor recently:
public TestClass(int test)
{
this.Test = Test;
}
不幸的是,在这里您没有StackOverflowException,现在您遇到了编程错误.在我的情况下,该值传递给WebService,而该WebService却使用默认值(不为0),这使我错过了我错误分配了它的事实.集成测试全部通过,因为此服务未显示
Unfortunately here you don't get a StackOverflowException, now you've got a programming error. In my case this value was passed to a WebService that instead used a default value (which wasn't 0) which caused me to miss the fact I had incorrectly assigned it. Integration tests all passed because this service didn't say
嘿,您忘记了这个非常重要的领域!"
"Hey you forgot this really important field!"
我可以采取哪些步骤来避免这种行为?始终建议我不要定义以下变量,并且我个人不喜欢它们,但是我想不出任何其他选择:
What steps can I take to avoid this sort of behaviour? I've always been advised against defining variables like the following, and I don't like them personally, but I can't think of any other options:
private int _test;
private int mTest;
编辑
下划线或m前缀通常是我不希望看到的,原因是:
Reasons that the underscore or m prefix are undesirable normally that I can think of are:
- 可读性
- 如果您是从3rd party类继承而来的,则滚动各种成员会更加困难,因为您会混合使用样式.
推荐答案
最好的方法是在此处使用自动实现的属性".
Best way is to use "Auto implemented properties" here.
public int Test { get; set; }
如果由于某种原因无法使用自动实现的属性",请使用 _
前缀(不过,我不喜欢).
If not possible to use "Auto implemented properties" for some reason use _
prefix(I don't prefer though).
如果您也不希望使用某些前缀,那么您还有其他选择.您不必手动编写属性代码.让IDE为您完成;这样,您可以避免粗心的错误.(我不知道我是怎么在原始答案中错过这个的)
If you also don't prefer to use some prefixes, then you have other option. You don't have to write the property code by hand. Let the IDE do it for you; that way you can avoid careless mistakes. (I don't know how I missed this in original answer)
只需输入
private int test;
选择字段,右键单击重构"->封装字段".IDE将为您生成属性片段,如下所示.
Select the field, Right click Refactor->Encapsulate Field. IDE will generate property snippet for you as below.
public int Test
{
get { return test; }
set { test = value; }
}
您无需费力单击上下文菜单.如果您更喜欢键盘,快捷方式是 Ctrl + R + E .
You don't need to bother clicking the context menu. If you prefer keyboard, shortcut is Ctrl + R + E.
或者得到一个Resharper,它将立即指出您的愚蠢错误.
Or get a Resharper, It will point your silly mistake immediately.
这篇关于如何避免财产递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!