Property backing value scope

前端 未结 6 1313
情书的邮戳
情书的邮戳 2021-02-12 19:10

Is anything like this possible? I\'m assuming not, but it looks good to me:

class MyClass {
    public int Foo {
        get { return m_foo; }
        s         


        
6条回答
  •  离开以前
    2021-02-12 19:36

    Here's my take on that:

    public class WrappedField
    {
        public class Internals
        {
            public T Value;
        }
    
        private readonly Internals _internals = new Internals();
        private readonly Func _get;
        private readonly Action _set;
    
        public T Value
        {
            get { return _get(_internals); }
            set { _set(_internals, value); }
        }
    
        public WrappedField(Func get, Action set)
        {
            _get = get;
            _set = set;            
        }
    
        public WrappedField(Func get, Action set, T initialValue)
            : this(get, set)
        {
            _set(_internals, initialValue);
        }
    }
    

    Usage:

    class Program
    {
        readonly WrappedField _weight = new WrappedField(
            i => i.Value,           // get
            (i, v) => i.Value = v,  // set
            11);                    // initialValue
    
        static void Main(string[] args)
        {
            Program p = new Program();
            p._weight.Value = 10;
    
            Console.WriteLine(p._weight.Value);
        }
    }
    

提交回复
热议问题