get,set and value keyword in c#.net

前端 未结 3 1910
夕颜
夕颜 2020-12-29 13:14

What is value keyword here and how is it assigning the value to _num? I\'m pretty confused, please give the description for the following code.

相关标签:
3条回答
  • 2020-12-29 13:47

    In the context of a property setter, the value keyword represents the value being assigned to the property. It's actually an implicit parameter of the set accessor, as if it was declared like this:

    private int _num
    public int num
    { 
        get 
        {
            return _num;
        }
        set(int value)
        {
            _num=value;
        }
    }
    

    Property accessors are actually methods equivalent to those:

    public int get_num()
    {
        return _num;
    }
    
    public void set_num(int value)
    {
        _num = value;
    }
    
    0 讨论(0)
  • 2020-12-29 13:58

    The value keyword is a contextual keyword, that is, it has a different meaning based on its context.

    Inside a set block, it simply means the value that the programmer has set it to. For instance,

    className.num = 5;
    

    In this case, value would be equal to 5 inside of the set block. So you could write:

    set
    {
        int temp = value; //temp = 5
        if (temp == 5) //true
        {
            //do stuff
        }
        _num = value;
    }
    

    Outside of a set block, you can use value as a variable identifier, as such:

    int value = 5;
    

    Note that you cannot do this inside a set block.

    Side note: You should capitalize the property num to Num; this is a common convention that makes it easier for someone who's reading your class to identify public and private properties.

    0 讨论(0)
  • 2020-12-29 13:58

    Properties are the way you can READ, WRITE or COMPUTE values of a private field or class variable. The set or setter inside a property is used when the code assigns a value into the private field or (class) variable. The value keyword means simply "the thing that is being assigned".

        public class StaffMember 
        { 
            private int ageValue; 
            public int Age 
                { 
                     set 
                         { 
                             if ( (value > 0) && (value < 120) ) 
                                 { this.ageValue = value; } 
                         } 
                     get { 
                          return this.ageValue; 
                         } 
                } 
        }
    //Rob Miles - C# Programming Yellow Book
    
    0 讨论(0)
提交回复
热议问题