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

前端 未结 11 1255
旧时难觅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:14

    Yes, you may use the Decorator Design Pattern.

    0 讨论(0)
  • 2021-01-03 19:16

    Not generally; a few options though;

    • inherit from ContextBoundObject - which does allow this, but at a performance cost
    • write an explicit property (i.e. with a backing field), and add a utility method call manually
    • look at compile-time weavers, such as PostSharp - generally by spotting an attribute or similar
    • look at runtime code generators, as offered by some DI/IoC tools (and some other "decorator" based tools) - which either decorate or subclass your object to add the extra code
    0 讨论(0)
  • 2021-01-03 19:16

    Are you in a position to rewrite your class to implement an interface? If so, Unity's interface interceptor might give you what you need. If an interface is not an option then that link also documents Unity's type and instance interceptors.

    0 讨论(0)
  • 2021-01-03 19:17

    Mocking frameworks can do this, as well as IoC libraries like Unity. The only other way to do such a thing would be to use IL-rewriting (as previously mentioned).

    0 讨论(0)
  • 2021-01-03 19:20

    Not out of the box. You would need to insert code into each properties setter and getter, either manually or automatically using IL rewriting.

    When you want to do it manually, you can't use automatic properties any more.
    When you want to do it automatically, have a look at AOP.

    0 讨论(0)
提交回复
热议问题