空属性声明的区别
可能的重复:
C# getter、setter 声明
这些属性声明之间有什么区别?它们如何工作以及为什么是首选。
public string aString {get;set;}
或
private string bString = "";
public string aString
{
get { return bString; }
set { bString = value; }
}
注意:这不是一个紧急或重要的问题,而是询问那些知道为什么应该以某种方式完成某事的人。另外,请举例说明哪种方案最适合每种实施。
Possible Duplicate:
C# getters, setters declaration
What's the difference between these property declarations ? How do they work and why is one preferred.
public string aString {get;set;}
OR
private string bString = "";
public string aString
{
get { return bString; }
set { bString = value; }
}
NOTE : THis is not a urgent or important question , rather a matter of asking the people who know why something should be done a certain way. Also, please give examples of which scenario is best for each implementation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第一个是自动属性,第二个是我们已知的经典属性。
当您没有任何特殊逻辑添加到 get 和 set 部分属性中时,您可以只使用自动属性,因为它的代码更少,更少的代码意味着更容易维护和更少的错误。
仅当需要在属性上添加一些逻辑(如验证)时,才应切换到经典属性语法。
First is automatic property and the second is classic property that we have known.
When you don't have any special logic to add in the get and set part property then you can just use automatic property since its less code and less code means easier maintenance and less bugs.
You should switch to classic property syntax only if you need to add some logic (like validation) on the property.
设计:
如果您需要在分配的确切时刻执行某些操作(引发事件、更改其他字段、保存撤消信息、写入文件以及大量其他可能性),请使用第二个。
实用:如果您只需要调试,请使用第二个,因为您不能在自动生成的属性上放置
断点
。在所有其他情况下首先使用。
Design:
Use second if you need to do something in exact moment of assignment (raise an event , change other fields, save undoredo information, write to a file and tons of other possibilities).
Practical: Use second if you need simply to debug, as you can not put a
breakpoint
on autogenerated property.Use first in all other cases.
最明显的区别是你不能设置 aString 变量并返回它,因为你总是返回 bString...
The most obvious difference is that you can't set the aString variable and return it, since you always return bString...
一个区别是,在自动属性的情况下,您不能拥有私有设置器。这只是一种语言快捷方式或语法糖,使开发变得更容易(而且生成的代码看起来更干净......)。
如果您查看编译后的程序集,编译器会生成与“经典”变体中完全相同的代码。
One difference is that in the case of automatic property you can't have a private setter. This is just a language shortcut or syntax sugar to make things easier to develop (also generated code looks cleaner...).
If you look at the compiled assembly the compiler made exact the same code as in the "classic" variation.