我有一个类,它有一个采用委托参数的方法,并且将通过反射调用它,例如:
namespace NSa
{
public delegate void dlg(string p1, string p2);
public class dyn
{
void method(dlg d)
{
// call d...
}
}
}
在另一堂课中,我需要dyn.method
用反射来调用:
namespace NSa
{
public delegate void dlg(string p1, string p2);
public void fun(string a, string b) { Console.Write(a); }
public class other
{
void caller_method()
{
dlg x = fun;
//...
var assembly = System.Reflection.Assembly.LoadFile("xx.dll");
System.Reflection.BindingFlags flags = (System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
System.Reflection.Module[] dynModules = assembly.GetModules();
Type dynType = dynModules[0].GetType("NSa.dyn");
object dynObj = Activator.CreateInstance(dynType);
System.Reflection.MethodInfo dynMethod = dynType.GetMethods(flags).Where(m => m.Name == "method").First();
dynMethod.Invoke(dynObj, new object[] {x});
}
}
}
我得到例外:
Object of type 'NSa.dlg' cannot be converted to type 'NSa.dlg'.
我错过了什么?