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

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

    Internally, getters and setters are just methods. When C# compiles, it generates methods for your getters and setters like this, for example:

    public int get_MyProperty() { ... }
    public void set_MyProperty(int value) { ... }
    

    C# allows you to declare these methods using a short-hand syntax. The line below will be compiled into the methods above when you build your application.

    public int MyProperty { get; set; }
    

    or

    private int myProperty;
    public int MyProperty 
    { 
        get { return myProperty; }
        set { myProperty = value; } // value is an implicit parameter containing the value being assigned to the property.
    }
    

提交回复
热议问题