C# getter and setter shorthand

前端 未结 5 1898
遥遥无期
遥遥无期 2021-02-13 06:24

If my understanding of the internal workings of this line is correct:

public int MyInt { get; set; }

Then it behind the scenes does this:

5条回答
  •  梦谈多话
    2021-02-13 07:02

    I'm going to add on to Simon Hughes' answer. I propose the same thing, but add a way to allow the decorator class to update a global IsDirty flag automatically. You may find it to be less complex to do it the old-fashioned way, but it depends on how many properties you're exposing and how many classes will require the same functionality.

    public class IsDirtyDecorator
    {
        private T _myValue;
        private Action _changedAction;
    
        public IsDirtyDecorator(Action changedAction = null)
        {
            _changedAction = changedAction;
        }
    
        public bool IsDirty { get; private set; }
    
        public T Value
        {
            get { return _myValue; }
            set
            {
                _myValue = value;
                IsDirty = true;
                if(_changedAction != null)
                    _changedAction(IsDirty);
            }
        }
    }
    

    Now you can have your decorator class automatically update some other IsDirty property in another class:

    class MyObject
    {
        private IsDirtyDecorator _myInt = new IsDirtyDecorator(onValueChanged);
        private IsDirtyDecorator _myOtherInt = new IsDirtyDecorator(onValueChanged);
    
        public bool IsDirty { get; private set; }
    
        public int MyInt
        {
            get { return _myInt.Value; }
            set { _myInt.Value = value; }
        }
    
        public int MyOtherInt
        {
            get { return _myOtherInt.Value; }
            set { _myOtherInt.Value = value; }
        }
    
        private void onValueChanged(bool dirty)
        {
            IsDirty = true;
        }
    
    }
    

提交回复
热议问题