c#仅使用方法名称(文本)向事件添加侦听器 [英] c# Adding a listener to Event with only the method name (text)
问题描述
我正在尝试使用反射将类中的方法添加到事件中。这是我的设置。
I am trying to use Reflection to add a method from a class to an event. Here is my setup.
- 使用keyPressDown& keyPressUp方法。我这堂课也有一个活动。 keyPressDown&
这些其他方法可控制RGB发光二极管。一种方法可以使颜色闪烁,另一种方法可以使颜色褪色,等等。
These additional methods are controlling RGB light emitting diodes. One method can flash a color, another can fade a color, etc..
-
我可以订阅类似myEventKeyUp + = myClass.MethodA的事件;
I can subscribe to the event like myEventKeyUp += myClass.MethodA;
我的问题是,我正在将用户想要的配置存储在数据库中。因此,我唯一想到的就是将方法名称存储为文本,并使用反射将其添加到事件处理程序中。
My problem is, I am storing the configuration the user wants in a database. So the only thing I can think of is storing the Method Name as text and use reflection to add it to the event handler.
代码示例:
Class MyClass
Class MyClass
public event delegateKeyDown keyDownEvent;
public event delegateKeyUp keyUpEvent;
public void KeyUp()
{
joystick.SetBtn(false, 1, vJoyButtonID);
if (keyUpEvent != null) keyUpEvent();
}
public void KeyDown()
{
joystick.SetBtn(true, 1, vJoyButtonID);
// IF WE HAVE ANY LISTENERS THEN FIRE THEM
if (keyDownEvent != null) keyDownEvent();
}
public void MethodA()
{
// DO SOMeTHING HERE
}
主窗体
button.keyDownEvent + = button.SetRandomColor;
button.keyDownEvent += button.SetRandomColor;
button.keyUpEvent + = button.TurnOff;
button.keyUpEvent += button.TurnOff;
我需要做的是:
button.keyUpEvent + = MyClass.GetType()。GetMethod( MethodA );
我知道您无法使用反射做我想做的事情,我读到我可以使用反射来获取包含事件处理程序的委托,并通过这种方式添加它,但是我不确定(或不清楚)。
I know you can't do what I am trying to do with Reflection, I read that I can use reflection to get hold of the delegate that contains the event handler, and add it through that way but I am unsure (or unclear about this).
推荐答案
在 Jim W 的链接中,这是一个有效的方法例如:
In the vein of Jim W's link, here's a working example:
using System;
using System.Reflection;
internal class Program
{
private static void Main()
{
var foo = new Foo();
var fooType = foo.GetType();
var eventInfo = fooType.GetEvent("Bar");
var methodInfo = fooType.GetMethod("OnBar", BindingFlags.Static | BindingFlags.Public);
eventInfo.AddEventHandler(foo, Delegate.CreateDelegate(eventInfo.EventHandlerType, methodInfo));
foo.RaiseBar();
Console.ReadKey();
}
}
public class Foo
{
public delegate void BarHandler(object sender, BarEventArgs args);
public event BarHandler Bar;
public void RaiseBar()
{
Bar(this, new BarEventArgs());
}
public static void OnBar(object sender, BarEventArgs args)
{
Console.WriteLine(args.Guid);
}
}
public class BarEventArgs : EventArgs
{
public Guid Guid => Guid.NewGuid();
}
这篇关于c#仅使用方法名称(文本)向事件添加侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!