Why we need Properties in C#

前端 未结 8 1179
萌比男神i
萌比男神i 2020-12-01 09:31

Can you tell me what is the exact usage of properties in C# i mean practical explanation

in our project we are using properties like

/// 

        
8条回答
  •  时光取名叫无心
    2020-12-01 10:12

    Here's a common pattern:

    class Foo {
    
        private Bar _bar;
    
        //here, Foo has a Bar object.  If that object has already been instantiated, return that value.  Otherwise, get it from the database.
        public Bar bar {
            set { _bar = value;}
            get {
                if (_bar == null) {
                    _bar = Bar.find_by_foo_name(this._name);
                }
                return _bar;
            }
        }
    }
    

    In short, this allows us to access the Bar object on our instance of Foo. This encapsulation means we don't have to worry about how Bar is retrieved, or if foo.bar has already been instantiated. We can just use the object and let the internals of the Foo class take care of it.

提交回复
热议问题