Looking for a short & simple example of getters/setters in C#

后端 未结 12 483
悲哀的现实
悲哀的现实 2020-12-07 12:35

I am having trouble understanding the concept of getters and setters in the C# language. In languages like Objective-C, they seem an integral part of the system, bu

12条回答
  •  忘掉有多难
    2020-12-07 12:59

    Most languages do it this way, and you can do it in C# too.

        public void setRAM(int RAM)
        {
            this.RAM = RAM;
        }
        public int getRAM()
        {
            return this.RAM;
        }
    

    But C# also gives a more elegant solution to this :

        public class Computer
        {
            int ram;
            public int RAM 
            { 
                 get 
                 {
                      return ram;
                 }
                 set 
                 {
                      ram = value; // value is a reserved word and it is a variable that holds the input that is given to ram ( like in the example below )
                 }
            }
         }
    

    And later access it with.

        Computer comp = new Computer();
        comp.RAM = 1024;
        int var = comp.RAM;
    

    For newer versions of C# it's even better :

    public class Computer
    {
        public int RAM { get; set; }
    }
    

    and later :

    Computer comp = new Computer();
    comp.RAM = 1024;
    int var = comp.RAM;
    

提交回复
热议问题