Property backing value scope

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

    Well, it's rather difficult to deal with, probably not very performant, and not something I'd really use, but technically it's a way of obscuring the backing field from the rest of the class.

    public class MySuperAwesomeProperty
    {
        private T backingField;
        private Func getter;
        private Func setter;
        public MySuperAwesomeProperty(Func getter, Func setter)
        {
            this.getter = getter;
            this.setter = setter;
        }
    
        public T Value
        {
            get
            {
                return getter(backingField);
            }
            set
            {
                backingField = setter(value);
            }
        }
    }
    
    public class Foo
    {
        public MySuperAwesomeProperty Bar { get; private set; }
    
    
        public Foo()
        {
            Bar = new MySuperAwesomeProperty(
                value => value, value => { doStuff(); return value; });
    
            Bar.Value = 5;
    
            Console.WriteLine(Bar.Value);
        }
    
        private void doStuff()
        {
            throw new NotImplementedException();
        }
    }
    

提交回复
热议问题