在C#中物业和现场之间的区别3.0+ [英] Difference between Property and Field in C# 3.0+
问题描述
我意识到,这似乎是一个重复的<一个href=\"http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c\">What是一个字段,并在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使用验证code。
有没有设置该属性有什么区别(除了款式/未来发展的),像一些类型的控制?
Is there any difference (except the style/future development ones), like some type of control in setting the property?
时之间有任何额外的区别:
Is there any additional difference between:
public string MyString { get; set; }
和
public string myString;
(我知道,那第一个版本需要C#3.0以上,编译器将创建一个private字段)。
(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.
另外,他们在不同的智能感知显示:)
Plus they show up differently in Intellisense :)
编辑:作为有机磷更新更新的问题 - 如果你想在这里忽略了其他的建议,另一个原因是,它根本就不是良好的面向对象设计。如果你没有一个很好的理由这样做,总是选择在一个公共变量/场的属性。
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+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!