I have the following two programs
WindowsFormsApplication
ClassLibrary1 dll
The ClassLibrary1 dll is loaded to the Windowsform via appdomain loading. I have subscibed to the dll events through reflection across the appdomain. I am trying to subscribe to the dll action(TestAction) and also handle the action in windows forms. But I get this error 'Object of type 'System.EventHandler' cannot be converted to type 'System.Action'
This is the windows form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using ClassLibrary1;
namespace WindowsFormsApplication2
{
[Serializable]
public partial class Form1 : Form
{
void HandleEvent(object sender, EventArgs e)
{
Debug.WriteLine("HandleEvent called");
}
void HandleAction(object sender, EventArgs e)
{
Debug.WriteLine("HandleAction called");
}
public Form1()
{
InitializeComponent();
Loader.Call( "RaiseEvent", HandleEvent, DateTime.Now.ToShortDateString());
Loader.Call( "RaiseAct", HandleAction, DateTime.Now.ToShortDateString());
}
private void button1_Click(object sender, EventArgs e)
{
Application.Restart();
Application.Run(new Form1());
this.Close();
}
}
public class Loader : MarshalByRefObject
{
static string dll = @"..\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll";
static AppDomain ad = AppDomain.CreateDomain("Test");
static Assembly a = Assembly.LoadFile(dll);
static object o = a.CreateInstance("ClassLibrary1.Class1");
static Type t = o.GetType();
object CallInternal1( string method, EventHandler handler, object[] parameters)
{
// Subscribe to the event
EventInfo eventInfo1 = t.GetEvent("TestEvent");
eventInfo1.AddEventHandler(o, handler);
MethodInfo m = t.GetMethod(method);
return m.Invoke(o, parameters);
}
object CallInternal2( string method, EventHandler handler, object[] parameters)
{
// Subscribe to the event
EventInfo eventInfo2 = t.GetEvent("TestAction");
eventInfo2.AddEventHandler(o, handler); // Error: Object of type 'System.EventHandler' cannot be converted to type 'System.Action
MethodInfo m = t.GetMethod(method);
return m.Invoke(o, parameters);
}
public static object Call( string method, EventHandler handler, params object[] parameters)
{
Loader ld = (Loader)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Loader).FullName);
object result = 0;
switch (method)
{
case "RaiseEvent":
{
result = ld.CallInternal1( method, handler, parameters);
break;
}
case "RaiseAct":
{
result = ld.CallInternal2( method, handler, parameters);
break;
}
}
return result;
}
}
}
Aucun commentaire:
Enregistrer un commentaire