What is the purpose of the “get” and “set” properties in C#

前端 未结 7 1576
鱼传尺愫
鱼传尺愫 2020-12-30 12:35

I saw some get set method to set values. Can anyone tell me the purpose of this?

public string HTTP_USER_NAME
{
      get 
      {
            return UserNam         


        
7条回答
  •  -上瘾入骨i
    2020-12-30 12:47

    From Properties (C# Programming Guide)

    A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

    In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

    Example

    class TimePeriod
    {
        private double seconds;
    
        public double Hours
        {
            get { return seconds / 3600; }
            set { seconds = value * 3600; }
        }
    }
    
    
    class Program
    {
        static void Main()
        {
            TimePeriod t = new TimePeriod();
    
            // Assigning the Hours property causes the 'set' accessor to be called.
            t.Hours = 24;
    
            // Evaluating the Hours property causes the 'get' accessor to be called.
            System.Console.WriteLine("Time in hours: " + t.Hours);
        }
    }
    // Output: Time in hours: 24
    

    Properties Overview

    • Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

    • A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. For more information, see Restricting Accessor Accessibility (C# Programming Guide).

    • The value keyword is used to define the value being assigned by the set accessor.

    • Properties that do not implement a set accessor are read only.

    • For simple properties that require no custom accessor code, consider the option of using auto-implemented properties. For more information, see Auto-Implemented Properties (C# Programming Guide).

提交回复
热议问题