Dynamic method overriding or observation when calling a method at runtime?

I am primarily an Objective-C / Cocoa developer, but I am trying to implement the Observer pattern in C # .NET, in particular, simulate the protocols and methodology of NSKeyValueObserving.

I went so far as to simulate manually supported NSKVOs as described in the Apple KVO Programming Guide (see http://tinyurl.com/nugolr ). Since I am writing the setValue: forKey: methods myself, I can implement automatic KVO notification.

However, I would like to somehow implement automatic KVO for all properties, dynamically redefining them at runtime. For example, replacing Button.Title.set with:

set { 
    this.willChangeValueForKey("title");
    title = value;
    this.didChangeValueForKey("title");
}

So this is my question:

How do I dynamically override a method or property at runtime in C #? I got before receiving and calling methods and properties by name using Reflection.MethodInfo. Alternatively, can I watch the runtime and find out when the method will / was called?

+3
source share
5 answers

After extensive research on this subject, it seems that I cannot do what I would like to do with .NET in its current state.

  • The PostSharp method is executed at compile time, that is, I cannot dynamically insert my own implementations into the methods.

  • Reflection.Emit allows me to do this dynamically, but it generates a new instance of the created subclass - I need to do this so that it works with the original instance.

  • INotifyPropertyChanging INotifyPropertyChanged , - .NET .

... , . , , , post . , .NET 4.0 !

0

- #. , PostSharp - .

INotifyPropertyChanged ( postsharp) , . , - , , , . ( ) #. PostSharp ( AOP/ -) .

+1

, . (.. ?), Emit. , .

0

, :

Using this material, you can track changes to specific properties and simplify implementation INotifyPropertyChanged(i.e. track changes to all properties).

0
source

Source: https://habr.com/ru/post/1714219/


All Articles