set(C# 参考)set (C# Reference)

set 关键字在属性或索引器中定义访问器 ,它会向属性或索引器元素分配值。The set keyword defines an accessor method in a property or indexer that assigns a value to the property or the indexer element. 有关详细信息和示例,请参阅属性自动实现的属性索引器For more information and examples, see Properties, Auto-Implemented Properties, and Indexers.

下面的示例为名为 Seconds 的属性同时定义 getset 访问器。The following example defines both a get and a set accessor for a property named Seconds. 它使用名为 _seconds 的私有字段备份属性值。It uses a private field named _seconds to back the property value.


class TimePeriod
{
     private double _seconds;

     public double Seconds
     {
         get { return _seconds; }
         set { _seconds = value; }
     }
}

通常,set 访问器包含分配一个值的单个语句,如前面的示例所示。Often, the set accessor consists of a single statement that assigns a value, as it did in the previous example. 从 C# 7.0 开始,可以将 set 访问器作为 expression-bodied 成员实现。Starting with C# 7.0, you can implement the set accessor as an expression-bodied member. 下面的示例将 getset 访问器都作为表达式主体成员实现。The following example implements both the get and the set accessors as expression-bodied members.


class TimePeriod
{
    private double _seconds;

    public double Seconds
    {
        get => _seconds;
        set => _seconds = value;
    }
}

对于属性的 getset 访问器不执行除设置或检索私有支持字段中的值以外的任何其他操作的简单情况,可以利用 C# 编译器对自动实现的属性的支持。For simple cases in which a property's get and set accessors perform no other operation than setting or retrieving a value in a private backing field, you can take advantage of the C# compiler's support for auto-implemented properties. 以下示例将 Hours 作为自动实现的属性来实现。The following example implements Hours as an auto-implemented property.

class TimePeriod2
{
    public double Hours { get; set; }
}

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also