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

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

    C# introduces properties which do most of the heavy lifting for you...

    ie

    public string Name { get; set; }
    

    is a C# shortcut to writing...

    private string _name;
    
    public string getName { return _name; }
    public void setName(string value) { _name = value; }
    

    Basically getters and setters are just means of helping encapsulation. When you make a class you have several class variables that perhaps you want to expose to other classes to allow them to get a glimpse of some of the data you store. While just making the variables public to begin with may seem like an acceptable alternative, in the long run you will regret letting other classes manipulate your classes member variables directly. If you force them to do it through a setter, you can add logic to ensure no strange values ever occur, and you can always change that logic in the future without effecting things already manipulating this class.

    ie

    private string _name;
    
    public string getName { return _name; }
    public void setName(string value) 
    { 
        //Don't want things setting my Name to null
        if (value == null) 
        {
            throw new InvalidInputException(); 
        }
        _name = value; 
    }
    

提交回复
热议问题