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

前端 未结 11 1370
旧时难觅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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 18:56

    Yes, of course...

    In your example you are using automatic properties, without a backing field.... You just need to create a backing field for your property, and then you can do what you want in the setter and getter.

    example:

    private string firstName;
    
    public string FirstName
    {
     get { return firstName; }
    
     set { doMethod(); firstName = value;}
    }
    

提交回复
热议问题