[C#] 字段(field),属性(property) 以及 get 和 set

字段应该永远为私有,私有字段自然是不许用户随便访问的,而属性实际上是一个写法有些特别的函数,为私有字段的访问提供接口,也就是通过属性读取私有域,或修改私有域,目的就是实现安全访问。
Java和C++都通过函数实现对私有变量的修改和访问,C#改成了属性的方式。
从C# 3.0 开始,支持自动实现的属性(Auto-Implemented Properties).

属性:

class OtherClass
{
    private string myString = "ohohoh"; // 私有字段
    public string MYssfsdfSTRING  // 属性。 随便编的一个名称ok,对属性名称并没有要求
    {
        set
        {
            myString = value;  // 这里value 和 set,get 一样,同为上下文关键字,不能改成别的名称。
        }
        get
        {
            return myString;
        }
    }
}
// 测试class里的Main函数
static void Main() {
    OtherClass obj = new OtherClass();
    obj.MYssfsdfSTRING = "123123123123123";  // set 
    Console.Write(obj.MYssfsdfSTRING); // get
}

上面的getset可以省略其一,属性就对应变为只写或只读, C#里的Main函数,不同于C/C++/Java, 首字母是大写的。

自动属性

public class Student
{
    public string StudentNumber { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string JobTitle { get; set; }
}

关于 getset 的正确和错误的写法:

// 错误
public string Name
{
    get { return str; }
    set;
}
//上面的写法错误的原因:
//The compilier creates a private, anonymous backing field that can only be //accessed through the property's get and set accessors.
//What you original code seems to be doing is get on a field you defined but a //set on the anonymous backing field. Therefore build error ...

// 错误
public string Name
{
    get { return str; }
    set;
}

// 正确
public string Name
{
    get { return str; }
    set { str = value; }
}

下面的两种写法也是错的:

// 错误
public string Name
{
    set;
}
// 错误
public string Name
{
    get;
}

Stack Overflow对属性和字段区别极为精简的答案:

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
{
    // 这就是 field.  It is private to your class and stores the actual data.
    private string _myField;

    // 这就是 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;
        }
    }

    // 这是 AutoProperty (C# 3.0 或更高 ) - which is a shorthand syntax
    // used to generate a private field for you
    public int AnotherProperty{get; set;} 
}

[1] https://stackoverflow.com/questions/14922286/c-sharp-get-set-properties
[2] https://stackoverflow.com/questions/8773181/c-sharp-field-vs-property
[3] https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property
[4] https://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0

猜你喜欢

转载自blog.csdn.net/ftell/article/details/81869626