Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

c# - 字段和属性之间有什么区别?(What is the difference between a field and a property?)

在C#中,是什么使字段不同于属性,以及何时应使用字段代替属性?

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Properties expose fields.

(属性公开字段。)

Fields should (almost always) be kept private to a class and accessed via get and set properties.

(字段(几乎总是)应该对类保持私有,并可以通过get和set属性对其进行访问。)

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 accessed it uses the underlying field,
    // but only exposes the contract, which will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }

    // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
    // used to generate a private field for you
    public int AnotherProperty{get;set;} 
}

@Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.

(@Kent指出,不需要Properties来封装字段,它们可以对其他字段进行计算或用于其他目的。)

@GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.

(@GSS指出,当访问属性时,您还可以执行其他逻辑,例如验证,这是另一个有用的功能。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...