如何声明和使用读/写属性(C# 编程指南)How to declare and use read write properties (C# Programming Guide)

属性提供了公共数据成员的便利性,且不会产生未受保护、不可控制和未经验证地访问对象的数据的风险。Properties provide the convenience of public data members without the risks that come with unprotected, uncontrolled, and unverified access to an object's data. 这通过访问器实现:从基础数据成员中赋值和检索值的特殊方法。This is accomplished through accessors: special methods that assign and retrieve values from the underlying data member. set 访问器可分配数据成员,get 访问器检索数据成员值。The set accessor enables data members to be assigned, and the get accessor retrieves data member values.

此示例演示具有两个属性的 Person 类:Name(字符串)和 Age(整型)。This sample shows a Person class that has two properties: Name (string) and Age (int). 这两个属性均提供 getset 访问器,因此它们被视为读/写属性。Both properties provide get and set accessors, so they are considered read/write properties.

示例Example

class Person
{
    private string _name = "N/A";
    private int _age = 0;

    // Declare a Name property of type string:
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }

    // Declare an Age property of type int:
    public int Age
    {
        get
        {
            return _age;
        }

        set
        {
            _age = value;
        }
    }

    public override string ToString()
    {
        return "Name = " + Name + ", Age = " + Age;
    }
}

class TestPerson
{
    static void Main()
    {
        // Create a new Person object:
        Person person = new Person();

        // Print out the name and the age associated with the person:
        Console.WriteLine("Person details - {0}", person);

        // Set some values on the person object:
        person.Name = "Joe";
        person.Age = 99;
        Console.WriteLine("Person details - {0}", person);

        // Increment the Age property:
        person.Age += 1;
        Console.WriteLine("Person details - {0}", person);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Person details - Name = N/A, Age = 0
    Person details - Name = Joe, Age = 99
    Person details - Name = Joe, Age = 100
*/

可靠编程Robust Programming

在前面的示例中,NameAge 属性为 public,同时包含 getset 访问器。In the previous example, the Name and Age properties are public and include both a get and a set accessor. 这使得任何对象均可读取和写入这些属性。This allows any object to read and write these properties. 但是,有时需要排除其中的一个访问器。It is sometimes desirable, however, to exclude one of the accessors. 例如,省略 set 访问器可使属性为只读:Omitting the set accessor, for example, makes the property read-only:

public string Name
{
    get
    {
        return _name;
    }
}

或者,可以公开一个访问器,但使另一个访问器为私有或受保护。Alternatively, you can expose one accessor publicly but make the other private or protected. 有关详细信息,请参阅非对称性访问器可访问性For more information, see Asymmetric Accessor Accessibility.

声明属性后,便可使用这些属性,就像它们是类的字段一样。Once the properties are declared, they can be used as if they were fields of the class. 在获取和设置属性的值时,这允许一种非常自然的语法,如以下语句所示:This allows for a very natural syntax when both getting and setting the value of a property, as in the following statements:

person.Name = "Joe";
person.Age = 99;

请注意,在属性 set 方法中,特殊的 value 变量为可用。Note that in a property set method a special value variable is available. 此变量包含用户指定的值,例如:This variable contains the value that the user specified, for example:

_name = value;

请注意在 Person 对象上递增 Age 属性的简洁语法:Notice the clean syntax for incrementing the Age property on a Person object:

person.Age += 1;

如果将单独的 setget 方法用于模型属性,则等效的代码可能如下所示:If separate set and get methods were used to model properties, the equivalent code might look like this:

person.SetAge(person.GetAge() + 1);

ToString 方法在此示例中被重写:The ToString method is overridden in this example:

public override string ToString()
{
    return "Name = " + Name + ", Age = " + Age;
}

请注意,ToString 未显式用于程序中。Notice that ToString is not explicitly used in the program. 默认情况下,通过 WriteLine 调用对其进行调用。It is invoked by default by the WriteLine calls.

请参阅See also