Property backing value scope

前端 未结 6 1317
情书的邮戳
情书的邮戳 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:32

    If you would like to avoid generics, you could always hide the _backingField and the bounds checking in a private inner class. You could even hide it further by making the outer class partial. Of course, there would have to be some delegating going on between the outer and the inner class, which is a bummer. Code to explain my thoughts:

    public partial class MyClass
    {
        public int Property
        {
            get { return _properties.Property; }
            set { _properties.Property = value; }
        }
    
        public void Stuff()
        {
            // Can't get to _backingField...
        }
    }
    
    public partial class MyClass
    {
        private readonly Properties _properties = new Properties();
    
        private class Properties
        {
            private int _backingField;
    
            public int Property
            {
                get { return _backingField; }
                set
                {
                    // perform checks
                    _backingField = value;
                }
            }
        }
    }
    

    But this is a lot of code. To justify all that boiler plate, the original problem has to be quite severe...

提交回复
热议问题