[英]How to create PropertyChangedEventHandler from method name
I'm newbie in OO programing and C#, and I would need some help.我是 OO 编程和 C# 的新手,我需要一些帮助。
I have several methods that could possibly be called upon a PropertyChanged event from a class member.我有几个方法可以在类成员的 PropertyChanged 事件上调用。 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.我自己还没有测试过,所以我不确定它会起作用,但也许它会让你朝着正确的方向前进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.