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

前端 未结 11 1254
旧时难觅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 18:55

    It is possible to do directly in the property body itself, but then you need to use a proper backing field instead of auto-implemented properties.

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

    Even with auto-implemented properties you get a backing field - this is generated by the compiler and you don't have direct access to it.


    Edit:

    Seeing as you don't want a backing field, you have other options - using an AOP tool such as PostSharp could help with that.

提交回复
热议问题