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

后端 未结 12 477
悲哀的现实
悲哀的现实 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:54

    In C#, Properties represent your Getters and Setters.

    Here's an example:

    public class PropertyExample
    {
        private int myIntField = 0;
    
        public int MyInt
        {
            // This is your getter.
            // it uses the accessibility of the property (public)
            get
            {
                return myIntField;
            }
            // this is your setter
            // Note: you can specify different accessibility
            // for your getter and setter.
            protected set
            {
                // You can put logic into your getters and setters
                // since they actually map to functions behind the scenes
                DoSomeValidation(value)
                {
                    // The input of the setter is always called "value"
                    // and is of the same type as your property definition
                    myIntField = value;
                }
            }
        }
    }
    

    You would access this property just like a field. For example:

    PropertyExample example = new PropertyExample();
    example.MyInt = 4; // sets myIntField to 4
    Console.WriteLine( example.MyInt ); // prints 4
    

    A few other things to note:

    1. You don't have to specifiy both a getter and a setter, you can omit either one.
    2. Properties are just "syntactic sugar" for your traditional getter and setter. The compiler will actually build get_ and set_ functions behind the scenes (in the compiled IL) and map all references to your property to those functions.

提交回复
热议问题