重构此 .Net 1.1 示例时如何利用自动属性?
我看到很多遗留的 .Net 1.1 风格的代码在工作,如下例所示,我想在自动属性的帮助下缩小它们。这将帮助许多班级缩小 30-40%,我认为这会很好。
public int MyIntThingy
{
get
{
return _myIntThingy;
}
set
{
_myIntThingy = value;
}
} private int _myIntThingy = -1;
这将变成:
public int MyIntThingy
{
get;
set;
}
唯一的问题是 - 我在哪里设置MyIntThingy = -1;
?
如果我从一开始就写这个课程,那么我会有一个更好的想法,但我没有。一个明显的答案是:将其放入构造函数中。问题是:这个类中有很多构造函数。在调试器中观察 -1
的初始化,我看到它发生在(我相信)构造函数被调用之前。这几乎就像我需要使用静态构造函数一样,如下所述: http://www.c-sharpcorner.com/uploadfile/cupadhyay/ staticconstructors11092005061428am/staticconstructors.aspx 除了我的变量不是静态的。我想到了 Java 的静态初始化器,但同样 - 我的变量不是静态的。 http://www.glenmccl.com/tip_003.htm
我想要风格化但不此类的功能更改。尽管它很糟糕,但它已经经过测试并工作了几年。破坏功能会很糟糕。所以......我正在寻找更短、更甜蜜、更可爱、但等效的代码。如果您有疑问,请告诉我。
I see a lot of legacy .Net 1.1-style code at work like in example below, which I would like to shrink with the help of an auto-property. This will help many classes shrink by 30-40%, which I think would be good.
public int MyIntThingy
{
get
{
return _myIntThingy;
}
set
{
_myIntThingy = value;
}
} private int _myIntThingy = -1;
This would become:
public int MyIntThingy
{
get;
set;
}
And the only question is - where do I set MyIntThingy = -1;
?
If I wrote the class from the start, then I would have a better idea, but I did not. An obvious answer would be: put it in the constructor. Trouble is: there are many constructors in this class. Watching the initialization to -1
in the debugger, I see it happen (I believe) before the constructor gets called. It is almost as if I need to use a static constructor as described here:
http://www.c-sharpcorner.com/uploadfile/cupadhyay/staticconstructors11092005061428am/staticconstructors.aspx
except that my variables are not static. Java's static initializer comes to mind, but again - my variables are not static. http://www.glenmccl.com/tip_003.htm
I want to make stylistic but not functional changes to this class. As crappy as it is, it has been tested and working for a few years now. breaking the functionality would be bad. So ... I am looking for shorter, sweeter, cuter, and yet EQUIVALENT code. Let me know if you have questions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
恐怕你别无选择。
如果您想使用初始值与类型的默认值不同的自动属性,那么您需要在构造函数中设置初始值。
I'm afraid that you have no option.
If you want to use an auto-property with an initial value that differs from the type's default value then you'll need to set the initial value in the constructor(s).
如果您只需要风格上的、不间断的更改,请考虑稍微更改一下格式:
这样不是更漂亮吗?
并考虑仅对未来的代码使用自动属性。在现有代码上使用它们听起来风险太大,除非没有默认值。
If you just need a stylistic, non-breaking change, consider changing the format a little:
Isn't that prettier?
And consider using auto-properties for future code only. It sounds too risky to use them on existing code, unless there are no default values.