Is there a way to intercept setters and getters in C#?

前端 未结 11 1448
旧时难觅i
旧时难觅i 2021-01-03 18:15

In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set*

11条回答
  •  感动是毒
    2021-01-03 19:09

    As far as I know, you have to use a backing field and put the call to the other method inside the setter thusly:

    public class Person {
        private string firstName;
        private string lastName;
    
        public string FirstName {
            set { 
                DoSomeStuff();
                firstName = value;
            }
            get { return firstName; }
        }
    
        public string LastName { 
            set {
                DoSomeStuff();
                lastName = value;
            }
            get { return lastName; }
        }
    }
    

提交回复
热议问题