Gerar um evento via reflexão em c #
eu queroescrever uma função reutilizável para criar um evento via reflexão.
Após a pesquisa, encontrei esta pergunta semelhante:Como eu levanto um evento via reflexão no .NET / C #?
Funciona até eu registrar um manipulador de eventos no controle WinForm e tentar invocá-lo. O campo privado "<EventName>
simplesmente desaparece.
Abaixo está o meu código simplificado que reproduz o problema:
Program.cs:
public static void Main()
{
Control control = new Control();
control.Click += new EventHandler(control_Click);
MethodInfo eventInvoker = ReflectionHelper.GetEventInvoker(control, "Click");
eventInvoker.Invoke(control, new object[] {null, null});
}
static void control_Click(object sender, EventArgs e)
{
Console.WriteLine("Clicked !!!!!!!!!!!");
}
Aqui está minha classe ReflectionHelper:
public static class ReflectionHelper
{
/// <summary>
/// Gets method that will be invoked the event is raised.
/// </summary>
/// <param name="obj">Object that contains the event.</param>
/// <param name="eventName">Event Name.</param>
/// <returns></returns>
public static MethodInfo GetEventInvoker(object obj, string eventName)
{
// --- Begin parameters checking code -----------------------------
Debug.Assert(obj != null);
Debug.Assert(!string.IsNullOrEmpty(eventName));
// --- End parameters checking code -------------------------------
// prepare current processing type
Type currentType = obj.GetType();
// try to get special event decleration
while (true)
{
FieldInfo fieldInfo = currentType.GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetField);
if (fieldInfo == null)
{
if (currentType.BaseType != null)
{
// move deeper
currentType = currentType.BaseType;
continue;
}
Debug.Fail(string.Format("Not found event named {0} in object type {1}", eventName, obj));
return null;
}
// found
return ((MulticastDelegate)fieldInfo.GetValue(obj)).Method;
}
}
Informação adicional:
Evento na mesma classe: funcionou.Evento em classe diferente, subclasse na mesma montagem: trabalhada.Evento emMEU modo diferente de montagem, depuração e liberação: funcionou.Evento no WinForm, DevExpress, ...: não funcionouQualquer ajuda é apreciada.