What is the purpose of accessors?

后端 未结 6 797
萌比男神i
萌比男神i 2021-02-13 02:09

Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.

6条回答
  •  旧时难觅i
    2021-02-13 03:16

    get{} and set{} are accessors that offer up the ability to easily read and write to private fields. Working with a simple example:

    public class Foo()
    { 
        //Field
        private int _bar;
    
        //Property
        public int Bar
        {
            get { return _bar; }
            set { _bar = value; }  
            //value is an implicit parameter to the set acccessor.
            //When you perform an assignment to the property, the value you
            //assign is the value in "value"
        }
    }
    

    In this case, Bar is a public property that has a getter and a setter that allows access to the private field _bar that would otherwise be inaccessible beyond class Foo.

    Now in a class that has an instace of Foo, you can do this:

    public class IHasAFoo()
    {
        private Foo _myFoo = new Foo();
    
        public void SomeMethod()
        {
            _myFoo.Bar = 42;
        }
    }
    

    So the public accessor allows you to set the value of the private field back in Foo.

    Hope that helps!

提交回复
热议问题