What is the purpose of accessors?

后端 未结 6 771
萌比男神i
萌比男神i 2021-02-13 02:09

Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.

6条回答
  •  梦如初夏
    2021-02-13 03:05

    They are called Accessors

    The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. The body of the get accessor resembles that of a method. It must return a value of the property type.

    http://msdn.microsoft.com/en-us/library/w86s7x04.aspx

    private string m_Name;   // the name field
    public string Name   // the Name property
    {
       get 
       {
          return m_Name; 
       }
    }
    

    The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property.

    private m_Name;
    public string Name {
        get {
            return m_Name;
        }
        set {
            m_Name = value;
        }
    }
    

    Then in the incarnation of C# 3, you can do this much easier through auto-properties

    public string Name {get; set; } // read and write
    public string Name {get; }  // read only
    public string Name { get; private set; } //read and parent write
    

    http://msdn.microsoft.com/en-us/library/bb384054.aspx

提交回复
热议问题