是什么场和C#中的属性之间的区别? [英] What is the difference between a Field and a Property in C#?
问题描述
在C#中,是什么让从属性的字段不同,什么时候应该字段用来代替属性?
In C#, what makes a field different from a property, and when should a field be used instead of a property?
推荐答案
属性暴露的字段。字段应该(总是)被保密的一类,并通过get和set属性进行访问。属性提供了一个抽象层,允许您更改领域,同时不影响它们被使用类的事情访问的外部方式。
Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.
public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When you access it uses the underlying field, but only exposes
// the contract that will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}
}
@Kent指出属性不要求封装字段,它们可以做在其他领域的计算,或用于其他目的。
@Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.
@GSS指出,你也可以做其他的逻辑,如验证,当一个属性被访问时,另一个有用的功能。
@GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.
这篇关于是什么场和C#中的属性之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!