简体   繁体   中英

How to create PropertyChangedEventHandler from method name

I'm newbie in OO programing and C#, and I would need some help.

I have several methods that could possibly be called upon a PropertyChanged event from a class member. A collection of that class is created based with data coming from a text file

I would like that the method to be called is also read from the text file like any other data (as string then).

How could I instanciate the event handlder and register to that event without giving the method as argument, but the method name instead, like:

var handler = new PropertyChangedEventHandler(MyHandler)
myData.PropertyChanged += (PropertyChangedEventHandler)handler;

I would like to achieve something like:

string str = "MyHandler";
var handler = new PropertyChangedEventHandler(str)
myData.PropertyChanged += (PropertyChangedEventHandler)str;`

I know that this is not working, but I don't know where to look to find a solution to this.

Thanks.

You could try using reflection to find the method and dynamically assign it to the delegate, something like:

public void AssignPropertyChangedMethod(string methodName)
{
    var methodInfo = this.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    var handler = Delegate.CreateDelegate(typeof(PropertyChangedEventHandler), this, methodInfo);
    myData.PropertyChanged += (PropertyChangedEventHandler)handler;
}

I haven't tested it myself so I am not sure it will work but maybe it will get you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM