get (C# 參考)get (C# Reference)

get 關鍵字會在屬性或索引子中定義「存取子」方法,以傳回屬性值或索引子項目。The get keyword defines an accessor method in a property or indexer that returns the property value or the indexer element. 如需詳細資訊,請參閱屬性自動實作的屬性索引子For more information, 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; }
     }
}

get 存取子通常是由傳回值的單一陳述式所組成,如上述範例所示。Often, the get accessor consists of a single statement that returns a value, as it did in the previous example. 從 C# 7.0 開始,您可以將 get 存取子實作為運算式主體成員。Starting with C# 7.0, you can implement the get accessor as an expression-bodied member. 下列範例會將 getset 存取子實作為運算式主體成員。The following example implements both the get and the set accessor 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