我意识到它似乎是 C# 中的字段和属性有什么区别? 但我的问题略有不同(从我的角度来看):
I realize that it seems to be a duplicate of What is the difference between a Field and a Property in C#? but my question has a slight difference (from my point of view):
一旦我知道
- 我不会将我的课程用于仅适用于属性的技术"和
- 我不会在 getter/setter 中使用验证码.
有什么区别吗(除了样式/未来开发的),比如设置属性时的某种类型的控件?
Is there any difference (except the style/future development ones), like some type of control in setting the property?
是否有任何其他区别:
public string MyString { get; set; }和
public string myString;(我知道,第一个版本需要 C# 3.0 或更高版本,并且编译器会创建私有字段.)
(I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.)
推荐答案封装.
在第二个实例中,您刚刚定义了一个变量,在第一个实例中,变量周围有一个 getter/setter.因此,如果您决定以后要验证该变量 - 会容易得多.
In the second instance you've just defined a variable, in the first, there is a getter / setter around the variable. So if you decide you want to validate the variable at a later date - it will be a lot easier.
此外,它们在 Intellisense 中的显示方式不同:)
Plus they show up differently in Intellisense :)
OP 更新问题的更新 - 如果您想忽略此处的其他建议,另一个原因是它根本不是好的 OO 设计.如果您没有充分的理由这样做,总是选择一个属性而不是公共变量/字段.
Update for OPs updated question - if you want to ignore the other suggestions here, the other reason is that it's simply not good OO design. And if you don't have a very good reason for doing it, always choose a property over a public variable / field.
更多推荐
C# 3.0+ 中属性和字段的区别
发布评论