C# getter and setter shorthand

前端 未结 5 1897
遥遥无期
遥遥无期 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 06:44

    Create an IsDirty decorator (design pattern) to wrap some your properties requiring the isDirty flag functionality.

    public class IsDirtyDecorator
    {
        public bool IsDirty { get; private set; }
    
        private T _myValue;
        public T Value
        {
            get { return _myValue; }
            set { _myValue = value; IsDirty = true; }
        }
    }
    
    public class MyClass
    {
        private IsDirtyDecorator MyInt = new IsDirtyDecorator();
        private IsDirtyDecorator MyString = new IsDirtyDecorator();
    
        public MyClass()
        {
            MyInt.Value = 123;
            MyString.Value = "Hello";
            Console.WriteLine(MyInt.Value);
            Console.WriteLine(MyInt.IsDirty);
            Console.WriteLine(MyString.Value);
            Console.WriteLine(MyString.IsDirty);
        }
    }
    

提交回复
热议问题