C# getter and setter shorthand

前端 未结 5 1899
遥遥无期
遥遥无期 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:52

    You can make it simple or complex. It depends on how much work you want to invest. You can use aspect oriented programming to add the aspect via an IL weaver into the IL code with e.g. PostSharp. Or you can create a simple class that does handle the state for your property. It is so simple that the former approach only pays off if you have really many properties to handle this way.

    using System;
    
    class Dirty
    {
        T _Value;
        bool _IsDirty;
    
        public T Value
        {
            get { return _Value; }
            set
            {
                _IsDirty = true;
                _Value = value;
            }
        }
    
        public bool IsDirty
        {
            get { return _IsDirty; }
        }
    
        public Dirty(T initValue)
        {
            _Value = initValue;
        }
    }
    
    class Program
    {
        static Dirty _Integer;
        static int Integer
        {
            get { return _Integer.Value; }
            set { _Integer.Value = value;  }
        }
    
        static void Main(string[] args)
        {
            _Integer = new Dirty(10);
            Console.WriteLine("Dirty: {0}, value: {1}", _Integer.IsDirty, Integer);
            Integer = 15;
            Console.WriteLine("Dirty: {0}, value: {1}", _Integer.IsDirty, Integer);
        }
    }
    

    Another possibility is to use a proxy class which is generated at runtime which does add the aspect for you. With .NET 4 there is a class that does handle this aspect already for you. It is called ExpandObject which does notify you via an event when a property changes. The nice things is that ExpandoObject allows you to define at runtime any amount of properties and you get notifications about every change of a property. Databinding with WPF is very easy with this type.

    dynamic _DynInteger = new ExpandoObject();
    
    _DynInteger.Integer = 10;
    ((INotifyPropertyChanged)_DynInteger).PropertyChanged += (o, e) =>
    {
        Console.WriteLine("Property {0} changed", e.PropertyName);
    };
    
    Console.WriteLine("value: {0}", _DynInteger.Integer );
    _DynInteger.Integer = 20;
     Console.WriteLine("value: {0}", _DynInteger.Integer);
    

    Yours, Alois Kraus

提交回复
热议问题